有一个带有两个按钮的简单UIViewController
,每次按下按钮时,都会将全屏幕视图添加到viewcontorller
的视图中,因为它的大小与viewcontroller
相同。
我们知道,如果一个视图重叠其parentView,则父录将无法响应任何事件。
但是,如果我按button0
,然后非常快速按button1
,则将视图添加到viewcontorller
,并且第二个按钮的触摸事件也将唤起。
这是我的代码:
@IBAction func button0Pressed(_ sender: Any) {
print(#function)
let view0 = UIView(frame: view.bounds)
view0.backgroundColor = UIColor.gray
let tap0 = UITapGestureRecognizer(target: self, action: #selector(tap0(_:)))
view0.addGestureRecognizer(tap0)
view.addSubview(view0)
}
@objc func tap0(_ gestureRecognizer: UITapGestureRecognizer) {
print(#function)
let view = gestureRecognizer.view
view?.removeFromSuperview()
}
@IBAction func button1Pressed(_ sender: Any) {
print(#function)
let view1 = UIView(frame: view.bounds)
view1.backgroundColor = UIColor.lightGray
let tap1 = UITapGestureRecognizer(target: self, action: #selector(tap1(_:)))
view1.addGestureRecognizer(tap1)
view.addSubview(view1)
}
@objc func tap1(_ gestureRecognizer: UITapGestureRecognizer) {
print(#function)
let view = gestureRecognizer.view
view?.removeFromSuperview()
}
out put:
button0Pressed
button1Pressed
那么,按下button0
之后,如何防止viewcontroller
S快速触摸事件?
您可以尝试将两个按钮(Button0和button1)作为IBOutlet
,并分配touchUpInside
事件以触发button0press/button1press函数。然后,您可以使用按下按钮0的enable
按钮1 after x seconds
(在我的示例中为1秒)。还有Viceversa。
@IBOutlet weak var button0: UIButton!
@IBOutlet weak var button1: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button0.addTarget(self, action: #selector(button0Pressed), for: .touchUpInside)
button1.addTarget(self, action: #selector(button1Pressed), for: .touchUpInside)
}
@objc func button0Pressed() {
print(#function)
let view0 = UIView(frame: view.bounds)
view0.backgroundColor = UIColor.gray
let tap0 = UITapGestureRecognizer(target: self, action: #selector(tap0(_:)))
view0.addGestureRecognizer(tap0)
view.addSubview(view0)
// Enable button1 after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1000)) {
self.button1.isEnabled = true
}
}
@objc func button1Pressed() {
print(#function)
let view1 = UIView(frame: view.bounds)
view1.backgroundColor = UIColor.lightGray
let tap1 = UITapGestureRecognizer(target: self, action: #selector(tap1(_:)))
view1.addGestureRecognizer(tap1)
view.addSubview(view1)
// Enable button0 after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1000)) {
self.button0.isEnabled = true
}
}