【发布时间】:2016-10-20 03:21:33
【问题描述】:
我正在尝试在我的 iOS 应用程序的最前面的窗口中添加一个(背景)遮罩视图。在那个掩码视图上,我想添加一个将关闭掩码视图的 UITapGestureRecognizer。最终,我想在中间显示一个弹出窗口(即我的蒙版视图是弹出窗口的褪色背景),但现在我只是无法让我的背景按预期消失。
代码如下所示:我得到最前面的窗口。我创建背景视图并添加 alpha。然后我添加我的手势识别器,将其添加到窗口并添加约束。
但是我的点击手势目标didTapOnMaskView() 永远不会被触发。
private func createMaskView() {
let applicationKeyWindow = UIApplication.shared.windows.last
backgroundView = UIView()
backgroundView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.backgroundColor = UIColor(white: 0, alpha: 0.2)
backgroundDismissGesture = UITapGestureRecognizer(target: self, action: #selector(didTapOnMaskView))
backgroundDismissGesture.numberOfTapsRequired = 1
backgroundDismissGesture.cancelsTouchesInView = false;
backgroundView.addGestureRecognizer(backgroundDismissGesture)
backgroundView.isUserInteractionEnabled = true
backgroundView.alpha = 0.0
UIView.animate(withDuration: 0.4) {
self.backgroundView.alpha = 1.0
}
applicationKeyWindow.addSubview(backgroundView)
let views: [String: UIView] = [ "backgroundView": backgroundView]
var allConstraints = [NSLayoutConstraint]()
let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[backgroundView]-0-|", options: [], metrics: nil, views: views)
allConstraints += verticalConstraint
let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[backgroundView]-0-|", options: [], metrics: nil, views: views)
allConstraints += horizontalConstraint
NSLayoutConstraint.activate(allConstraints)
// This is super odd, but the gesture gets triggered until the following code block executes
DispatchQueue.main.asyncAfter(deadline: .now() + 3.1) {
applicationKeyWindow.bringSubview(toFront: self.backgroundView)
}
}
func didTapOnMaskView() {
hide()
}
func show(){
createMaskView()
}
** 编辑 **
在运行了更多诊断之后,我注意到如果我在 createMaskView() 的末尾添加一个延迟三秒的代码块,将 maskView 带到前面,则手势在前 3.1 秒内有效,直到该块的代码被执行。请注意,如果该代码块不存在,则手势识别器根本不起作用(甚至 3.1 秒)。
【问题讨论】:
标签: swift cocoa-touch automatic-ref-counting swift3 uitapgesturerecognizer