[英]The oldValue value in the property observer is always the same in Swift
嗨,我有collectionView,並且我的自定義單元格中有一個radioButton。我在我的集合視圖的cellforAt function 中分配了cell.radioButton.tag = indexPath.row。然后,我創建了一個如下所示的屬性觀察器。 我單擊不同的數據,但 oldValue 正在以相同的值打印。 (你可以在照片中看到我點擊了射手和戰略。)
var selectedIndex: Int = 0 {
didSet {
print("old \(oldValue), current \(selectedIndex)")
}
}
@IBAction func tappedRadioButton(_ sender: UIButton) {
self.selectedIndex = sender.tag
}
您應該將selectedIndex
變量存儲在您的視圖 controller 中,而不是存儲在您的單元格中。
您在單元格本身中添加了 selectedIndex ,因此每個單元格都在創建自己的 object 初始值為 0,這是錯誤的,您需要將此屬性添加到 viewController 本身並通過委托或閉包進行更改
//add this closure to your cell
var didTapRadioButton: (() -> Void)?
//call this closure in the @IBAction for the radio button
@IBAction....{
didTapRadioButton?()
}
//from ViewController cellforRow(at IndexPath..
cell.didTapRadioButton = {
self.selectedIndex = indexPath.row
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.