[英]Removing UIView via UITapGestureRecognizer requires 2 clicks (swift)
选择一个按钮时,我创建了一个覆盖整个屏幕的视图。 具体来说,我的UICollectionViewCell中有一个UIButton,单击该按钮时,它将在设备的整个窗口上呈现叠加层。 叠加层是一个UIView层次结构,其中UIVisualEffectView是叠加层的父视图。 选择上述UIButton时,会将UIVisualEffectView作为子视图添加到ViewController.view属性。
我还向UIVisualEffectView添加了UITapGestureRecognizer。 选中后,整个叠加层应通过从ViewController.view子视图中移除而消失。
唯一的问题是UITapGestureRecognizer的行为。 我必须单击两次以使覆盖消失。 添加跟踪打印语句表明,第一次单击时会触发UITapGestureRecognizer操作#selector函数,但是直到我再次单击它或单击模拟器框架(即,移动模拟器)时,叠加层才会消失正确地。 我怀疑这可能与线程和返回控制有关,但无法查明。 以下是相关代码。 任何帮助表示赞赏。
注意:我已经在DispatchQueue.main.async()块中有和没有removeFromSuperview语句的情况下运行了此代码; 无论有没有,行为都是一样的。
在UIViewController子类中进行设置:
var blurBackground = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.dark))
blurBackground.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(unblurView)))
目标操作,已通过跟踪语句确认触发:
func unblurView() {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
print("In unblur func")
self.blurBackground.alpha = 0.0
DispatchQueue.main.async(execute: {
self.blurBackground.removeFromSuperview()
print("In unblur func - main thread removefromsuperview")
})
}, completion: nil)
}
如果有帮助,我可以添加与将叠加层视图添加到视图控制器视图的子视图有关的代码。
使用以下视图控制器创建一个新的Single View App项目对我来说很好
class ViewController: UIViewController {
var blurBackground = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.dark))
override func viewDidLoad() {
super.viewDidLoad()
blurBackground.frame = self.view.frame
blurBackground.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.unblurView)))
view.addSubview(blurBackground)
}
@objc func unblurView() {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
print("In unblur func")
self.blurBackground.alpha = 0.0
DispatchQueue.main.async(execute: {
self.blurBackground.removeFromSuperview()
print("In unblur func - main thread removefromsuperview")
})
}, completion: nil)
}
}
您如何将blurBackground添加到视图?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.