我有viewcontroller
,它已分成两个视图。一个是视图,其中视图由{{1}的tableviewcontroller
的{{1}}组成,另一个是childcontroller
,它是当tableviewcontroller viewcontroller
didselectrowatindexpath {{1} }当我致电statusview
时,请在状态视图中重新加载我的数据。我可以在s
中释放数据,但是状态视图不能反映数据。
深灰色区域是状态视图,中间视图是is called. but when i can
。
didselectrowatindexpath
通过此代码,我可以将数据重新加载到tableview
中。但是,当我使用parentController(viewcontroller)的tableview
或override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.reloadData()
}
时会崩溃。我该如何解决这个问题?
答案 0 :(得分:0)
在这种情况下,您将需要以下两个选项之一:
UIViewController
将要实现的协议,以便UITableViewController
可以通过委托将数据传递到其父视图控制器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)
}
}