简体   繁体   English

通过 UIViewController 传递触摸

[英]Pass touches through a UIViewController

I have a view controller that I overlay on top of another view controller.我有一个视图控制器,我覆盖在另一个视图控制器之上。 I just need the top view controller so I can overlay a temporary pop up notification, and having an overlayed VC allows me to present this over a UITableViewController as you can't add subviews to tableview controllers directly.我只需要顶视图控制器,这样我就可以覆盖一个临时的弹出通知,并且有一个覆盖的 VC 允许我在 UITableViewController 上呈现它,因为你不能直接将子视图添加到 tableview 控制器。

Is it possible to interact with the bottom view controller while it has another view controller covering it.是否有可能与底部视图控制器交互,同时它有另一个视图控制器覆盖它。 If this were a view or a window you would achieve this by setting user interaction to false or using hitTest but neither of these approaches works for a view controller.如果这是一个视图或窗口,您可以通过将用户交互设置为 false 或使用 hitTest 来实现,但这些方法都不适用于视图控制器。

Create subclass like this像这样创建子类

class TouchDelegatingView: UIView {
    weak var touchDelegate: UIView? = nil


    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let view = super.hitTest(point, with: event) else {
            return nil
        }

        guard view === self, let point = touchDelegate?.convert(point, from: self) else {
            return view
        }

        return touchDelegate?.hitTest(point, with: event)
    }
}

Then in your ViewController set view class (you can do it directly in xib, or inside loadView() method)然后在您的 ViewController 中设置视图类(您可以直接在 xib 中或在 loadView() 方法中进行)

And add并添加

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        if let delegatingView = view as? TouchDelegatingView {
            delegatingView.touchDelegate = presentingViewController?.view
        }
    }
}

Also you can use this mechanism to delegate touches to any other view, no matter if it您也可以使用此机制将触摸委托给任何其他视图,无论它是否

As you've correctly deduced, when you present one view controller over another, the presenting view controller's view is not in the responder chain. 正如您正确推断的那样,当您将一个视图控制器呈现在另一个视图控制器上时,呈现视图控制器的视图不在响应者链中。 Touches in the presented view controller's view therefore cannot "fall through" to it. 因此,所呈现的视图控制器视图中的触摸不能“落入”它。 You will have to route your message from the presented view controller's view in some other way. 您必须以其他方式从显示的视图控制器的视图中路由您的消息。

You don't have access to previous ViewController, and user can't interact by touch with it. 您无权访问以前的ViewController,用户无法通过触摸进行交互。 Property modalPresentationStyle = .OverCurrentContext just means that views under presented content are not removed from the view hierarchy. 属性modalPresentationStyle = .OverCurrentContext仅表示不会从视图层次结构中删除所呈现内容下的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM