【问题标题】:Swift: Protocol and Delegates passing data to previous view controllerSwift:将数据传递给前一个视图控制器的协议和委托
【发布时间】:2020-12-22 18:33:37
【问题描述】:

我在 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 时,什么也没有发生。表格视图不会重新加载,标签也不会更改为按下的类别。我错过了什么吗?

【问题讨论】:

  • 请注意:协议应大写,如protocol CategoryPressed: class {

标签: ios swift delegates


【解决方案1】:

代表可能为零。你在ViewDidLoad 方法中添加了这一行吗?

delegate = self

【讨论】:

  • 我在第二个 vc 中如何称呼它?
  • @magellan ViewDidLoad 通常很好,正如答案所暗示的那样
  • 是的,正如@aheze 建议的那样,ViewDidLoad 是最好的地方
【解决方案2】:

在从 VC1 移动到 VC2 时,您可能错过了将委托分配给自己。

希望下面的代码对你有所帮助。

//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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多