我试图在我的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秒)。
答案 0 :(得分:0)
由于您希望您的背景视图与其超级视图具有相同的大小,您可以尝试设置帧大小而不是使用约束。
let backgroundView = UIView(frame: applicationKeyWindow.frame)
过去在类似的情况下对我有用。
我希望这有帮助!祝你有愉快的一天!
答案 1 :(得分:0)
事实证明,没有维护对包含我的maskView的View的引用是个问题。在创建此View的ViewController中,我更改了showPopUp()
函数,如下所示:
// Stored property on my View Controller class
var myPopupView: UIView?
private func showLMBFormSubmittedPopup(){
let popupView = MyPopupView()
popupView.show()
// Once I added this line, it started working
myPopupView = popupView
}
也许有人可以阐明为什么会这样。我怀疑ARC释放了UITapGestureRecognizer
占用的内存,因为我的代码不再引用它。