【问题标题】:iOS - How to pass down tap gesture without changing the underneath UIViewController?iOS - 如何在不更改下面的 UIViewController 的情况下传递点击手势?
【发布时间】:2021-10-19 09:08:40
【问题描述】:

我有两个视图控制器,B 显示在 A 之上,但不是全屏显示。我正在使用 UIPresentationController 来自定义 B 的框架。我想要的是,当点击 A 时,B 被解除并且 A 响应它自己的点击手势。

如何在 B 和 UIPresentationController 中实现这一点,而不涉及 A 的代码?

我尝试为 B 添加全屏背景视图,但不知道如何在不更改 A 的情况下将点击手势向下传递。

【问题讨论】:

    标签: ios uitapgesturerecognizer uipresentationcontroller


    【解决方案1】:

    自定义一个背景视图,pointInside 方法总是返回 false 以忽略触摸事件并在返回之前执行任何需要的操作,例如关闭 B。

    class BackgroundView: UIView {
        override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            // anything you want
            return false
        }
    }
    

    将自定义背景视图添加到 UIPresentationController。将containerView的isUserInteractionEnabled设置为false,否则UITransitionView会阻塞触摸事件向下传递。

    class MyPresentationController: UIPresentationController {
        var backgroundView: BackgroundView = BackgroundView()
        var containerFrame: CGRect = UIScreen.main.bounds
        
        override var frameOfPresentedViewInContainerView: CGRect {
            return CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 300)
        }
        
        override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
            super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
            self.backgroundView.backgroundColor = UIColor.yellow
            self.backgroundView.alpha = 0.5
            self.backgroundView.translatesAutoresizingMaskIntoConstraints = false
        }
        
        override func presentationTransitionWillBegin() {
            self.containerView?.addSubview(self.backgroundView)
            self.containerView?.isUserInteractionEnabled = false // !!!
        }
        
        override func containerViewDidLayoutSubviews() {
            super.containerViewDidLayoutSubviews()
            self.containerView?.frame = self.containerFrame
            self.backgroundView.frame = self.containerFrame
            self.presentedView?.frame = self.frameOfPresentedViewInContainerView
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 2019-04-06
      • 1970-01-01
      • 2012-06-02
      • 2011-12-12
      • 1970-01-01
      • 2011-09-01
      相关资源
      最近更新 更多