【问题标题】:Removing UIView via UITapGestureRecognizer requires 2 clicks (swift)通过 UITapGestureRecognizer 删除 UIView 需要 2 次点击 (swift)
【发布时间】:2018-04-23 01:42:35
【问题描述】:

我创建了一个在选择按钮时覆盖整个屏幕的视图。具体来说,我的 UICollectionViewCell 中有一个 UIButton,当单击它时,它会在设备的整个窗口上呈现叠加层。叠加层是一个 UIView 层次结构,其中 UIVisualEffectView 是叠加层的父视图。在选择上述UIBUTTON时,将添加UIVISUBEFFEFFECTVIEW作为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)
}

如果有帮助,我可以将与添加覆盖视图相关的代码添加到视图控制器视图的子视图中。

【问题讨论】:

    标签: ios iphone swift uiview uikit


    【解决方案1】:

    使用以下视图控制器创建一个新的单视图应用程序项目对我来说很好

    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 添​​加到视图中?

    【讨论】:

    • 在您发表评论后,我尝试在我的 MBP 上运行它,它正在工作。问题出在我的 Hackintosh 上——不确定这是否与此有关。真的很奇怪。尽管如此,我认为由于 blurBackground 动画,用户必须等到动画完成,然后 TapGesture 才会关闭。这听起来像预期的行为吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多