gpt4 book ai didi

ios - 如何访问委托(delegate)函数中的变量?

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

我有一个类MyCell,它有一个委托(delegate)和一个实例变量tagToIndex。我想在委托(delegate)修改后打印这个变量。目前我的代码如下所示:

 class MyCell: UITableViewCell, YSSegmentedControlDelegate {

var tagToIndex: Dictionary<Int,Int>?

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

tagToIndex[actionButton.tag] = index

}


print(tagToIndex)
}

问题在于,tagToIndex 不是打印委托(delegate)函数 (willPressItemAt) 中存在的 tagToIndex,而是 tagToIndex 为零。

我还尝试使用回调将索引发送回 View Controller 。代码如下所示:

var switchTapIndex: ((Int)->Void)?

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


switchTapIndex?(index)

}

不幸的是,当我在单独的函数中打印该值时,该值仍然返回“nil”。也许我无法完全理解回调是如何工作的,但我不明白我所做的与在 switch 函数中使用回调有什么不同,如下所示:

var switchTapAction : ((Bool)->Void)?
func switched(_ sender: UISwitch) {
print("Switched: \(sender.isOn)")

// send the Switch state in a "call back" to the view controller
switchTapAction?(sender.isOn)
}

最佳答案

在这里,您可能会得到 tagToIndex 为 nil,因为您没有初始化该变量。只要尝试一下,

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

}


print(tagToIndex)
}

关于ios - 如何访问委托(delegate)函数中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44702663/

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