Is there a built-in way to get from a UIView
to its UIViewController
? I know you can get from UIViewController
to its UIView
via [self view]
but I was wondering if there is a reverse reference?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
To Phil's answer:
In line:
id nextResponder = [self nextResponder];
if self(UIView) is not a subview of ViewController's view, if you know hierarchy of self(UIView) you can use also:id nextResponder = [[self superview] nextResponder];
...My solution would probably be considered kind of bogus but I had a similar situation as mayoneez (I wanted to switch views in response to a gesture in an EAGLView), and I got the EAGL's view controller this way:
Since this has been the accepted answer for a long time, I feel I need to rectify it with a better answer.
Some comments on the need:
An example of how to implement it follows:
The view interfaces with its delegate (as
UITableView
does, for instance) and it doesn't care if its implemented in the view controller or in any other class that you end up using.My original answer follows: I don't recommend this, neither the rest of the answers where direct access to the view controller is achieved
There is no built-in way to do it. While you can get around it by adding a
IBOutlet
on theUIView
and connecting these in Interface Builder, this is not recommended. The view should not know about the view controller. Instead, you should do as @Phil M suggests and create a protocol to be used as the delegate.I would suggest a more lightweight approach for traversing the complete responder chain without having to add a category on UIView:
I stumbled upon a situation where I have a small component I want to reuse, and added some code in a reusable view itself(it's really not much more than a button that opens a
PopoverController
).While this works fine in the iPad (the
UIPopoverController
presents itself, therefor needs no reference to aUIViewController
), getting the same code to work means suddenly referencing yourpresentViewController
from yourUIViewController
. Kinda inconsistent right?Like mentioned before, it's not the best approach to have logic in your UIView. But it felt really useless to wrap the few lines of code needed in a separate controller.
Either way, here's a swift solution, which adds a new property to any UIView:
Updated version for swift 4 : Thanks for @Phil_M and @paul-slm