我想在UIView
被按下后突出显示,松开后返回正常颜色。如何最好地实现这个功能?
创建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
}
}
关于重写touchesBegan
和touchesEnded
,苹果公司提供以下建议:
在创建自己的子类时,调用super方法以转发任何您不处理的事件。如果您重写此方法而没有调用super(这是常见的用法模式),则还必须覆盖其他处理触摸事件的方法[即
touchesEnded
、touchesMoved
、touchesCancelled
],即使您的实现什么也不做。
进一步阅读:
非常简单的例子 - 您可以在Playground页面上运行它:
//: 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()
实际上,你需要一些额外的代码来检查状态、处理touchesCancelled
等。
这只是为了让你开始学习 - 在以下网址上阅读关于触摸事件的更多信息:https://developer.apple.com/documentation/uikit/uiview
UIButton
。 - rmaddy