有一个简单的UIViewController
有两个按钮,每按一个按钮,全屏视图将被添加到viewcontorller
的视图,因为它的大小与viewcontroller
相同。
我们知道如果视图与其父视图重叠,则父视图无法响应任何事件。
但是,如果我按下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()
}
出局:
button0Pressed
button1Pressed
那么,如何在按下viewcontroller
后阻止button0
s快速触摸事件?
您可以尝试将两个按钮(button0和button1)设置为IBOutlet
并指定touchUpInside
事件以触发button0Press / button1Press功能。然后你可能有enable
button1 after x seconds
(在我的例子中为1秒)按下了button0。反之亦然。
@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
}
}