如果将 UIView 添加为 UIViewControler 视图的子视图,并且不向 UIView 添加事件。UIViewControler的方法将被调用。但是,如果将 UIView 添加为 UIButton 的子视图,并且不向 UIView 添加事件,则不会调用按钮单击事件。所以这让我感到困惑。当您添加按钮作为UIView的子视图时,也会发生这种情况,按钮没有添加目标操作方法,它的超级视图(UIView)也没有像这样调用方法。
假设您的问题是这样的:为什么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
被触发而不是控制器的。添加
发生这些事情是因为当您点击按钮时,点击按钮而不是控制器的视图优先,因为从按钮开始的每次触摸都计为点击。