我有一个 UIView 的子类。在本类(class)中,我想在更改特定 bool 标志时更改背景。 (我通过 touchesBegan
控制这个标志)
下面是我的代码。
class TileView: UIView {
let selectedBackgroundColor: UIColor = .cyan
let nonSelectedBackgroundColor: UIColor = .white
private var isSelected = false {
didSet {
backgroundColor = isSelected ? self.selectedBackgroundColor : self.nonSelectedBackgroundColor
print("isSelected: " + String(isSelected))
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isSelected = !isSelected
}
}
当 touchesBegan
被触发时,我在控制台中得到 isSelected: true
但背景颜色没有改变。
我注意到,在 View 中点击后,如果我点击 View 之外屏幕上的其他位置,它会改变颜色。
我很困惑到底是什么原因造成的。
编辑:
这里是行为的简短记录,因为我的描述不够清楚。 录制中的每个白色方 block 都是一个 TileView。 https://gyazo.com/e8152d18b4efe1c5b1c6c04b55b661fe
最佳答案
所以我发现我的代码没问题,问题实际上是模拟器没有正确更新。 有关更多详细信息,请参阅此处的答案。
关于iOS Swift UI 更新延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59595944/