I have a pointer to a UIView
. How do I access its UIViewController
? [self superview]
is another UIView
, but not the UIViewController
, right?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- Could I create “Call” button in HTML 5 IPhone appl
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
- How do you detect key up / key down events from a
The fast and generic way in Swift 3:
I think you can propagate the tap to the view controller and let it handle it. This is more acceptable approach. As for accessing a view controller from its view, you should maintain a reference to a view controller, since there is no another way. See this thread, it might help: Accessing view controller from a view
From the
UIResponder
documentation fornextResponder
:So, if you recurse a view’s
nextResponder
until it is of typeUIViewController
, then you have any view’s parent viewController.Note that it still may not have a parent view controller. But only if the view has not part of a viewController’s view’s view hierarchy.
Swift 3 and Swift 4.1 extension:
Swift 2 extension:
Objective-C category:
This macro avoids category pollution:
If you are not familiar with the code and you want to find ViewController coresponding to given view, then you can try:
In most cases you will get UIView, but from time to time there will be UIViewController based class.
If you set a breakpoint, you can paste this into the debugger to print the view hierarchy:
You should be able to find your view's parent somewhere in that mess :)
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.