gpt4 book ai didi

ios - 如何/在哪里设置委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 12:22:11 24 4
gpt4 key购买 nike

我正在努力通过委托(delegate)传递函数中存在的变量。在大多数情况下,一切似乎都有效。我唯一不明白的是如何设置委托(delegate),例如它应该类似于 "foo".delegate = self

通常这很简单,但由于我正在使用函数而不是类中的变量,所以我不知道 foo 会是什么(请原谅行话,我需要占位符)

供大家引用

这是协议(protocol):

protocol TagToIndexDelegate {
func finishPassing (dictionary:Dictionary<Int,Int>)
}

这是我尝试发送变量的函数:

extension MyCell: YSSegmentedControlDelegate {

func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) {
tagToIndex[actionButton.tag] = index

delegate?.finishPassing(dictionary: tagToIndex)
}

func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int) {

}}

其中delegate的类型为TagToIndexDelegatewillPressItemAt中存在的变量tagToIndex是我的数据我路过。

最后,我试图实现的类 TagToIndexDelegate

class AnswerViewController: UIViewController, TagToIndexDelegate {

func finishPassing (dictionary: Dictionary <Int, Int>)
{

}


override func viewDidLoad() {
super.viewDidLoad()

}
}

我对使用委托(delegate)还很陌生,因此非常感谢任何帮助或批评。

谢谢

尼克

最佳答案

假设 AnswerViewController 是包含问题中引用的 TableView 和单元格的 View Controller ,它也可能是 TableView 数据源。

您在其中创建 MyCell 实例的 UITableViewDataSource 实现可能如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "my_cell_reuse_id") as! MyCell
return aCell
}

您所要做的只是将委托(delegate)设置为self:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "my_cell_reuse_id") as! MyCell
aCell.delegate = self
return aCell
}

请注意,我假设 delegateMyCell 的属性:

class MyCell: UITableViewCell {
var delegate: TagToIndexDelegate?
}

关于ios - 如何/在哪里设置委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44665264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com