假设我们有两个 View Controller ,一个带有标签的父 View 和一个带有 TableView 的模态呈现的 subview 。我如何使用委托(delegate)将用户在 TableView 中的选择传递回父级?
ViewController1:
var delegate: vc2delegate?
override func viewDidLoad {
super.viewDidLoad()
let label.text = ""
}
ViewController2:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
let selections = ["1", "2", "3", "4", "5"]
cell.selections.text = selections[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? Cell {
cell.didSelect(indexPath: indexPath as NSIndexPath)
}
dismiss(animated: true, completion: nil)
}
//wherever end of class is
protocol vc2delegate {
// delegate functions here
}
我有正确的方法吗?我从来没有真正理解过这种模式,我认为学习 iOS 对我来说至关重要。另一个棘手的警告可能是当您关闭模态视图 Controller 时不会调用 viewDidLoad() 。
最佳答案
看看 UIViewController 生命周期 docs : ViewDidLoad 只被调用一次。
关于如何执行此操作的指南很多,只需快速搜索一下即可。 您需要更新数据源逻辑,因为我添加了一个快速字符串数组,您很可能会遇到更复杂的东西,但想法仍然相同。
顺便说一句,我使用了你的 vc1/vc2 命名约定,但我希望你的 Controller 有更有意义的名称。
在您的代码中,您在错误的 VC 上设置了委托(delegate)。这是它应该是什么样子的快速代码示例:
class VC1: UIViewController {
let textLabel = UILabel()
// whenever you're presenting the vc2
func presentVC2() {
var vc2 = VC2()
vc2.delegate = self
self.present(vc2, animated: true, completion: nil)
}
}
extension VC1: VC2Delegate {
func updateLabel(withText text: String) {
self.textLabel.text = text
}
}
protocol VC2Delegate: class {
func updateLabel(withText text: String)
}
class VC2: UIViewController {
weak var delegate: VC2Delegate?
let dataSource = ["string 1", "tring 2"]
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let string = dataSource[indexPath.row]
self.delegate?.updateLabel(withText: string)
dismiss(animated: true, completion: nil)
}
}
关于ios - 从模态呈现的 View Controller 传回数据的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60677831/