【问题标题】:How to access a variable within a Delegate Function?如何访问委托函数中的变量?
【发布时间】:2017-06-24 09:51:56
【问题描述】:

我有一个类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,而是 nil。

我还尝试使用回调将索引发送回视图控制器。代码如下所示:

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)
}

【问题讨论】:

  • 如果要在delegate修改后打印,为什么print语句在相关方法之外?
  • 我不仅要打印它,我还要在课堂的其他地方实际使用变量。
  • 您需要停止一遍又一遍地发布相同的问题。坚持一个问题……回答人们的问题……如果你没有得到你想要的答案,那么你需要考虑你在问什么,并试着弄清楚你想要做什么。
  • 我不太确定如何更清楚。如果你能告诉我你不明白的部分,那将对我有很大帮助。这个问题对我来说很有意义,但对其他人可能没有意义。

标签: ios swift delegates


【解决方案1】:

在这里,您可能会得到 tagToIndex 为零,因为您没有初始化该变量。试试看,

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

    }


    print(tagToIndex)
    }

【讨论】:

    【解决方案2】:

    以下行将tagToIndex 声明为Dictionary&lt;Int, Int&gt;? 类型的属性。换句话说,它是从IntInt 的可选Dictionary 映射。可选属性默认为nil。由于你还没有初始化它,它是nil

    var tagToIndex: Dictionary&lt;Int,Int&gt;?

    通过删除? 使该属性成为非可选属性,并对其进行初始化:

    var tagToIndex: Dictionary&lt;Int,Int&gt; = [:]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 2020-02-14
      相关资源
      最近更新 更多