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?
问题:
回答1:
Subclass the UIView
and keep your view controller lean.
class CustomUIView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.blue
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("touch start")
backgroundColor = UIColor.red
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
print("touch ended")
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, even if your implementations do nothing.
This example only illustrates your question. Subclassing UIView
can become relatively involved so here are a couple of good starting points:
https://developer.apple.com/documentation/uikit/uiview
Proper practice for subclassing UIView?
回答2:
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