选中时更改自定义UIView背景

Stu*_*rtM 0 objective-c uiview uicolor ios

UIViews创建了三个自定义圈.当用户点击其中一个时,我想将视图的背景颜色更改为灰色.

最初创建视图时,它是randomColor.如果再次选择视图,我希望这种颜色保持不变.即,再次选择时,从颜色变为灰色,然后变为灰色.

更改视图背景或在我的自定义UIView中添加叠加层以使其变灰的最佳方法是什么?

Edu*_*ias 7

当"selected"具有视图的子类并添加触摸事件时,一种更改视图背景的方法.

class CustomView: UIView {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.backgroundColor = UIColor.selected
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.backgroundColor = UIColor.default
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.backgroundColor = UIColor.default
    }
}
Run Code Online (Sandbox Code Playgroud)