如何解决Swift:协议和委托将数据传递给之前的视图控制器
我在 Swift 中工作,但未调用函数 categorypressedFunction
。
协议:
protocol categorypressed: class { //1 create a protocol with function that passes a string
func categorypressedFunction(category: String)
}
视图控制器 2:
//set the delegate
weak var delegate: categorypressed?
//when cell is selected in tableview,grab the "category" which is a string and then dismiss
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
let category = guideCategoryArray[indexPath.row] // gets category
delegate?.categorypressedFunction(category: category) // sets delegate to kNow it was pressed
self.presentingViewController?.dismiss(animated: true,completion: nil) //dismisses
}
}
视图控制器 1(上一个)
//set class delegate
...categorypressed
//add function that sets label to category and looks up items based off category
func categorypressedFunction(category: String) {
print("categorypressedFunctionpressed")
resourceArray.removeAll()
resourceLabel.text = category
getItems(item: category,{ [self] in
print("got new items for \(category) and refreshed the tableview")
self.resourceTableView.reloadData()
})
}
返回到 ViewController 1 时,什么也没有发生。 tableview 不会重新加载,标签也不会更改为按下的类别。我错过了什么吗?
解决方法
代表可能为零。您是否在 ViewDidLoad
方法中添加了这一行?
delegate = self
,
在从 VC1 移动到 VC2 时,您可能错过了将委托分配给 self 的操作。
希望下面的代码对您有所帮助。
//Some Navigation logic
let VC2 = UIStoryboard(name: "Main",bundle: nil).instantiateViewController(withIdentifier: "VC2Identifier") as! VC2;
VC2.delegate = self
self.present(VC2,animated: true,completion: nil)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。