繁体   English   中英

Swift:协议和委托将数据传递到前一个视图 controller

[英]Swift: Protocol and Delegates passing data to previous view controller

我在 Swift 工作,并且没有调用 function categoryPressedFunction PressedFunction。

协议:

protocol categoryPressed: class { //1 create a protocol with function that passes a string
    func categoryPressedFunction(category: String)
}

查看 Controller 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
}
}

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

代表可能为零。 您是否在ViewDidLoad方法中添加了这一行?

delegate = self

在从 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM