ios - 如何在 View 之间传递数据。我应该什么时候使用什么?

标签 ios swift uitableview inheritance parent-child

我有一个像这样的 View 层次结构:

  • UIViewController (SingleEventViewController)
    • UIScrollView (EventScrollView)
      • UIView (contentView)
        • 3xUITableView (SurePeopleTV, MaybePeopleTV, NopePeopleTV (all inherited from the same UITableView)), & all other UI-Elements

SingleEventViewController 存储一个事件(在初始化程序中传递)。 (所有事件都存储在核心数据中)。

三个 UITableViews 用于显示参与(或不参与或可能参与)事件的用户。我的问题是,用数据填充 tableView 的可能性有哪些?在哪种情况下您会推荐什么。


目前我在所有 subview 中都有一个属性 parentVC: SingleEventViewController 并像这样获取数据:

override func loadUsers() {
//class SurePeopleTV
    guard let parentController = parentVC else { return }
    users = (parentController.thisEvent.eventSureParticipants?.allObjects as! [User])
    finishedLoading = true
    super.loadUsers()
}

.

func applyDefaultValues() {
//class EventScrollView
    guard let parent = parentVC else { return }
    titleLabel.text = parent.eventName
}

我是编程新手,但我觉得我不应该在我的所有类中创建 parentVC 引用。

最佳答案

一个对象不应该(理想情况下)知道它的父对象——如果知道的话,它们就是“紧密耦合的”。如果您更改对象的父级,您的代码可能会中断。在您的情况下,您的父对象必须具有 thisEvent 属性。

您希望您的对象“松散耦合”,因此该对象不知道特定的父对象。

在 Swift 中,传递信息“备份链”的常用方法是使用委托(delegate)设计模式……https://developer.apple.com/documentation/swift/cocoa_design_patterns或使用闭包。

另见 https://www.andrewcbancroft.com/2015/04/08/how-delegation-works-a-swift-developer-guide/有关代表团的信息

关于ios - 如何在 View 之间传递数据。我应该什么时候使用什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52513131/

相关文章:

ios - 迪尔德 : Symbol not found: _OBJC_CLASS_$_UIUserNotificationSettings when trying to run on iOS7

ios - Firebase 推送转化事件

ios - Swift 将箭头和 sourceView 添加到 UIAlertController

swift - 无效的诊断签名

ios - 表格 View 中的下拉列表

ios - 重置图标角标(Badge)计数

swift - 如何使 CoreData 模型符合协议(protocol)?

ios - 内存泄漏: steady increase in memory usage with simple device motion logging

ios - 将 UITableView 添加到 UIPageViewController 时,“无法识别的选择器发送到实例”

ios - 如何使用enum获取字符串值