假设您的问题是这样的:为什么点击UIButton 不会让UIViewController 视图的touchesBegan 方法被调用?
让我们看一下这个实验项目,为了简单起见,我使用了框架而不是约束。
import UIKit
class MyButton: UIButton {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("BUTTON TOUCHES BEGAN")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let view1 = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
view1.backgroundColor = .black
self.view.addSubview(view1)
let button = MyButton(type: .custom)
button.frame = CGRect(x: 200, y: 100, width: 100, height: 100)
button.setTitle("XXX", for: .normal)
button.backgroundColor = .yellow
button.setTitleColor(.black, for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
let view2 = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view2.backgroundColor = .red
button.addSubview(view2)
}
@objc func buttonClicked() {
print("buttonClccked")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("TOUCHES BEGAN")
}
}
你提到的每一个案例我都做过。
view1 是普通视图。将其添加为控制器视图的子视图,然后点击它会触发控制器中的touchesBegan。这很好。
view2 被添加为按钮的子视图,无论是否占用按钮的整个框架,然后您点击view2,按钮的touchesBegan 将被触发而不是控制器的。添加
这些事情发生是因为当您点击按钮时,按钮的点击优先于控制器的视图,因为从按钮开始的每次触摸都被计为点击。