I want to change color of UIView
when it's tap and change it back to it's original color after tap event
I already implemented these 2 methods but their behavior is not giving me required results
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
}
These 2 methods work but after press tap on UIView
for 2 seconds then it works. Moreover it doesn't change the color of UIView
back to white after pressing it (In short it stays gray until I restart the app) I am using tap gestures on UIView
Instead of overriding touchesBegan
and touchesEnded
methods, you could add your own gesture recognizer. Inspired from this answer , you could do something like:
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
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.