我想在点击UIView
时更改其颜色,并在点击事件后将其恢复为原始颜色
我已经实现了这两种方法,但是它们的行为并未给我所需的结果
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
backgroundColor = UIColor.white
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
backgroundColor = UIColor.gray
}
这2种方法都可以,但是在按住UIView
的同时点击2秒钟,然后就可以使用。此外,按下UIView
后,它的颜色不会变回白色(总之直到我重新启动应用程序,它都会保持灰色)
我在UIView
答案 0 :(得分:1)
您可以添加自己的手势识别器,而不是覆盖touchesBegan
和touchesEnded
方法。受this answer的启发,您可以执行以下操作:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
setupTap()
}
func setupTap() {
let touchDown = UILongPressGestureRecognizer(target:self, action: #selector(didTouchDown))
touchDown.minimumPressDuration = 0
view.addGestureRecognizer(touchDown)
}
@objc func didTouchDown(gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
view.backgroundColor = .white
} else if gesture.state == .ended || gesture.state == .cancelled {
view.backgroundColor = .gray
}
}
}