为什么在集合视图单元格中以编程方式创建的按钮需要是惰性变量?
Why does a button created programmatically in a collection view cell need to be a lazy var?
如果我在 collectionView 单元格中以编程方式创建按钮,如果我想触发添加的目标,为什么我需要将按钮设置为惰性变量而不是常量?
例如,
class Cell: UICollectionViewCell {
let xButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(handleX), for: .touchUpInside)
return button
}()
@objc func handleX() {
print("123")
}
...other boiler plate code
}
如果选择按钮,123 永远不会打印,但如果我将按钮设置为惰性变量:
class Cell: UICollectionViewCell {
lazy var xButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(handleX), for: .touchUpInside)
return button
}()
@objc func handleX() {
print("123")
}
...other boiler plate code
}
打印 123。
我理解lazy stored 属性是一个属性,它的初始值直到第一次使用才被计算。我不明白为什么它对 UIButton 很重要。
除非像 addTarget()
.
那样需要实例本身,否则不必延迟初始化变量
您需要将按钮创建为 lazy
,以便您可以访问 self
,只有在创建单元格后才能访问该按钮。因此,问题不在于按钮本身的创建,而是需要访问 self
.
的 target/action 的设置
或者,您可以稍后在将按钮添加到单元格的视图层次结构时分配 target/action。
如果我在 collectionView 单元格中以编程方式创建按钮,如果我想触发添加的目标,为什么我需要将按钮设置为惰性变量而不是常量?
例如,
class Cell: UICollectionViewCell {
let xButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(handleX), for: .touchUpInside)
return button
}()
@objc func handleX() {
print("123")
}
...other boiler plate code
}
如果选择按钮,123 永远不会打印,但如果我将按钮设置为惰性变量:
class Cell: UICollectionViewCell {
lazy var xButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(handleX), for: .touchUpInside)
return button
}()
@objc func handleX() {
print("123")
}
...other boiler plate code
}
打印 123。
我理解lazy stored 属性是一个属性,它的初始值直到第一次使用才被计算。我不明白为什么它对 UIButton 很重要。
除非像 addTarget()
.
您需要将按钮创建为 lazy
,以便您可以访问 self
,只有在创建单元格后才能访问该按钮。因此,问题不在于按钮本身的创建,而是需要访问 self
.
或者,您可以稍后在将按钮添加到单元格的视图层次结构时分配 target/action。