iOS Swift 延迟更新到 UI

iOS Swift Update to UI delayed

我有一个 UIView 的子class。在此 class 中,我想在更改特定布尔标志时更改背景。 (我通过touchesBegan控制这个flag)

下面是我的代码。

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 但背景颜色没有改变。

我注意到在点击视图后,如果我点击视图外屏幕上的其他地方,它会改变颜色。

我对可能导致此问题的原因感到困惑。

编辑:

由于我的描述不够清楚,这里是对行为的简短记录。 录音中的每个白色方块都是一个 TileView。 https://gyazo.com/e8152d18b4efe1c5b1c6c04b55b661fe

所以我发现我的代码没有问题,问题实际上是模拟器没有正确更新。 有关更多详细信息,请参阅此处的答案。