Given a view, how do I get its viewController?

后端 未结 13 747
北海茫月
北海茫月 2020-11-28 02:00

I have a pointer to a UIView. How do I access its UIViewController? [self superview] is another UIView, but not the

13条回答
  •  醉酒成梦
    2020-11-28 02:34

    The fast and generic way in Swift 3:

    extension UIResponder {
        func parentController(of type: T.Type) -> T? {
            guard let next = self.next else {
                return nil
            }
            return (next as? T) ?? next.parentController(of: T.self)
        }
    }
    
    //Use:
    class MyView: UIView {
        ...
        let parentController = self.parentController(of: MyViewController.self)
    }
    

提交回复
热议问题