当UITapGestureRecognizer
没有添加到视图中时,UIButton
和CustomControl
都将接收.touchUpInside
事件.然而,当将UITapGestureRecognizer
添加到视图中时,只有UIButton
可以接收.touchUpInside
事件.在此场景中,如何将定制UIControl
配置为像UIButton
一样响应touch 事件?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let uiButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
uiButton.backgroundColor = .red
uiButton.addTarget(self, action: #selector(onUIButtonClick), for: .touchUpInside)
view.addSubview(uiButton)
let customButton = CustomControl(frame: CGRect(x: 200, y: 100, width: 100, height: 100))
customButton.backgroundColor = .blue
customButton.addTarget(self, action: #selector(onCustomControlClick), for: .touchUpInside)
view.addSubview(customButton)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
view.addGestureRecognizer(tapGesture)
}
@objc func onTap() {
debugPrint("onTap")
}
@objc func onUIButtonClick() {
debugPrint("onUIButtonClick")
}
@objc func onCustomControlClick() {
debugPrint("onCustomControlClick")
}
}
class CustomControl: UIControl {
}