简体   繁体   中英

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.

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.

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)

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. Property modalPresentationStyle = .OverCurrentContext just means that views under presented content are not removed from the view hierarchy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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