How does UIView nextResponder know what the UIViewController is?

后端 未结 4 1829
暗喜
暗喜 2021-02-07 20:05

Just as a matter of curiosity, how does the nextResponder method implementation of the UIView class know who is the UIViewController that manages the view? The UIResponder docum

相关标签:
4条回答
  • 2021-02-07 20:16

    My guess is that the system may maintain a mapping between UIViewController objects and their root UIView objects. The code for traversal of responder chain may use this mapping to pass the event to the corresponding UIViewController object.

    Typically subviews are added using:

    subview = [viewController view]

    [superview addSubview subview]

    addSubview method automatically sets superview as the next responder for subview, so:

    a) viewController wont have the opportunity to insert itself between superview and subview.

    b) viewController does not know about superview, hence it cannot set it as its next responder.

    c) Apple recommends that a view may not be shared across controllers. In absence of multi-threading this restriction makes sense only if there is a map of views and view controllers.

    0 讨论(0)
  • 2021-02-07 20:21

    If you look at UIView.h, you can see a member variable named _viewDelegate that is of type UIViewController*, this is probably where the view controller reference is stored when the viewcontroller's view property is set, and where it knows to look when you call nextResponder.

    0 讨论(0)
  • 2021-02-07 20:21

    there is actually a private api on uiview to get the uiviewcontroller it belongs to. Very handy ;) My guess is when a view is added to a view controller(controller.view) this property is set.

    0 讨论(0)
  • 2021-02-07 20:27

    The responder chain is separate from the view hierarchy. The responder chain might look like this:

    First Responder > View Hierarchy > Window > Window Delegate > etc...
    

    However, objects can insert themselves into the responder chain and that's what UIViewController does. From the docs:

    Because view controllers are tightly bound to the views they manage, they are also part of the responder chain used to handle events. View controllers are themselves descendants of the UIResponder class and are inserted into the responder chain between the managed view and its superview.

    In Big Cocoa, this is accomplished using the -setNextResponder: method. That method isn't public in Cocoa Touch, but nevertheless that's what UIViewController appears to do.

    0 讨论(0)
提交回复
热议问题