我有一个类MyCell
,它有一个委托和一个实例变量tagToIndex
。我想在委托人修改它之后打印这个变量。目前我的代码看起来是这样的:如何访问委托函数中的变量?
class MyCell: UITableViewCell, YSSegmentedControlDelegate {
var tagToIndex: Dictionary<Int,Int>?
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) {
tagToIndex[actionButton.tag] = index
}
print(tagToIndex)
}
的问题是,而不是打印tagToIndex
,因为它在委托函数(willPressItemAt
)存在,tagToIndex
是零。
我也尝试使用回调将索引发送回视图控制器。代码如下所示:
var switchTapIndex: ((Int)->Void)?
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) {
switchTapIndex?(index)
}
不幸的是,当我在单独的函数中打印该值时,该值仍然返回“无”。也许我没有完全理解回调是如何工作的,但我不知道怎么样我做的是不是使用像这样的开关函数内的回调有什么不同:
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)
}
,为什么是相关方法之外的'print'语句? – crizzis
[读取代理函数中存在的变量]的可能重复(https://stackoverflow.com/questions/44679900/reading-a-variable-that-exists-in-a-delegate-function) – crizzis
我不仅必须打印它,我必须在课程中的其他位置实际使用该变量。 –