如何在iOS的子控制器中快速更新数据

时间:2018-08-31 06:36:54

标签: ios swift view reloaddata

我有viewcontroller,它已分成两个视图。一个是视图,其中视图由{{1}的tableviewcontroller的{​​{1}}组成,另一个是childcontroller,它是当tableviewcontroller viewcontroller didselectrowatindexpath {{1} }当我致电statusview时,请在状态视图中重新加载我的数据。我可以在s中释放数据,但是状态视图不能反映数据。 enter image description here

深灰色区域是状态视图,中间视图是is called. but when i can

didselectrowatindexpath

通过此代码,我可以将数据重新加载到tableview中。但是,当我使用parentController(viewcontroller)的tableviewoverride func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.reloadData() } 时会崩溃。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在这种情况下,您将需要以下两个选项之一:

  1. 创建主要UIViewController将要实现的协议,以便UITableViewController可以通过委托将数据传递到其父视图控制器
  2. UITableViewController中发布UINotification,并在状态栏视图中接收此通知并显示数据。

让我们探索两个选项:

定义协议,在此示例中,我仅发送String所点击的单元格:

@objc protocol YourDataProtocol {
    func didSelectCell(withString string: String)
}

接下来,将委托属性添加到您的UITableViewController

class YourTableViewController: UIViewController {
    weak var delegate: YourDataProtocol?
...

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath)
        //call the delegate method with your text - in this case just text from textLabel
        if let text = cell?.textLabel?.text {
            delegate?.didSelectCell(withString: text)
        }
    }    
}

让您的UIViewContoller成为UITableViewController子类的委托:

class YourViewController: UIViewController, YourDataProtocol {
    ...
    let yourTableVC = YourTableViewController(...
    yourTableVC.delegate = self 

    func didSelectCell(withString string: String) {
        statusBar.text = string//update the status bar
    }
}

第二个选项与NotificationCenter一起使用

在您的UITableViewController中发布通知

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)

    if let text = cell?.textLabel?.text {
        let notificatioName = Notification.Name("DataFromTableViewCell")
        NotificationCenter.default.post(name: notificatioName, object: nil, userInfo: ["YourData": text])
    }
}

在状态栏中,您开始收听此通知

NotificationCenter.default.addObserver(self, selector: #selector(didReceiveData(_:)), name: notificatioName, object: nil)

@objc func didReceiveData(_ notification: Notification) {
    if let userData = notification.userInfo, let stringFromCell = userData["YourData"] {
        print(stringFromCell)
    }
}