我有一个应用程序,其中包含有关酒吧的信息。 listViewController 将每个 Bar 对象保存在单元格中(姓名、地址、电话等)。
当我按下单元格时,我移动到显示数据的 infoViewController,但由于某种原因它不起作用
这是TableView中的代码-
func tableView(_ tableView: UITableView, didSelectRowAt
indexPath: IndexPath) {
let barSelected = bars[indexPath.row]
let infoVC = storyboard?.instantiateViewController(withIdentifier: "infoViewController") as! InfoViewController
chooseBarDelegate?.chooseBar(barChosen: barSelected)
present(infoVC, animated: true, completion: nil)
该类符合我创建的协议(protocol) -
导入基础
protocol barInfoDelegate {
func chooseBar(barChosen:Bar)
}
我还创建了一个委托(delegate)实例 -
var chooseBarDelegate:barInfoDelegate?
在detailViewController中我创建了一个带有可选对象的var -
var infoBar:Bar?
并添加了扩展 -
extension InfoViewController: barInfoDelegate {
func chooseBar(barChosen: Bar) {
infoBar = barChosen
}
}
我还在 infoViewController 中将委托(delegate)设置为 self
listViewController.chooseBarDelegate? = self
应用程序不会崩溃,但信息不会传递。 当我使用打印对象检查调试器时,我可以看到“barSelected”确实包含一个对象,但 infoBar 为零。
我做错了什么?
谢谢!
最佳答案
根本没有委托(delegate)的理由。删除 InfoViewController
上的协议(protocol)、chooseBarDelegate
属性和 barInfoDelegate
扩展。您唯一需要保留的是 InfoViewController
的 var infoBar:Bar?
属性。
然后替换这一行:
chooseBarDelegate?.chooseBar(barChosen: barSelected)
与:
infoVC.infoBar = barSelected
关于swift - 如何使用委托(delegate)模式将对象传输到另一个 VC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774009/