I would like to make a UIView
highlighted after it's pressed and return to the normal color after release. What is the best practise for doing this?
Subclass the UIView
:
class CustomView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.blue
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
backgroundColor = UIColor.red
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
backgroundColor = UIColor.blue
}
}
Apple about overriding touchesBegan
and touchesEnded
:
When creating your own subclasses, call super to forward any events that you do not handle yourself. If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events [i.e.
touchesEnded
,touchesMoved
,touchesCancelled
], even if your implementations do nothing.
Further reading:
https://developer.apple.com/documentation/uikit/uiview
Proper practice for subclassing UIView?
Very simple example - you can run it in a Playground page:
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func viewDidLoad() {
view.backgroundColor = .red
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.backgroundColor = .green
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
view.backgroundColor = .red
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
In practice, though, you want some additional code to check state, handle touchesCancelled
, etc.
This is just to get you going - read up on touch events at: https://developer.apple.com/documentation/uikit/uiview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With