Given a view, how do I get its viewController?

后端 未结 13 589
北海茫月
北海茫月 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:29

    A little bit late, but here's an extension that enable you to find a responder of any type, including ViewController.

    extension NSObject{
    func findNext(type: AnyClass) -> Any{
        var resp = self as! UIResponder
    
        while !resp.isKind(of: type.self) && resp.next != nil
        {
            resp = resp.next!
        }
    
        return resp
      }                       
    }
    
    0 讨论(0)
  • 2020-11-28 02:34

    The fast and generic way in Swift 3:

    extension UIResponder {
        func parentController<T: UIViewController>(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)
    }
    
    0 讨论(0)
  • 2020-11-28 02:42

    If you set a breakpoint, you can paste this into the debugger to print the view hierarchy:

    po [[UIWindow keyWindow] recursiveDescription]
    

    You should be able to find your view's parent somewhere in that mess :)

    0 讨论(0)
  • 2020-11-28 02:43

    UIView has a variable called window ?

    So this will return a view controller

    you can access it like this self.window?.rootViewController

    0 讨论(0)
  • 2020-11-28 02:44

    Yes, the superview is the view that contains your view. Your view shouldn't know which exactly is its view controller, because that would break MVC principles.

    The controller, on the other hand, knows which view it's responsible for (self.view = myView), and usually, this view delegates methods/events for handling to the controller.

    Typically, instead of a pointer to your view, you should have a pointer to your controller, which in turn can either execute some controlling logic, or pass something to its view.

    0 讨论(0)
  • 2020-11-28 02:44

    More type safe code for Swift 3.0

    extension UIResponder {
        func owningViewController() -> UIViewController? {
            var nextResponser = self
            while let next = nextResponser.next {
                nextResponser = next
                if let vc = nextResponser as? UIViewController {
                    return vc
                }
            }
            return nil
        }
    }
    
    0 讨论(0)
提交回复
热议问题