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
While these answers are technically correct, including Ushox, I think the approved way is to implement a new protocol or re-use an existing one. A protocol insulates the observer from the observed, sort of like putting a mail slot in between them. In effect, that is what Gabriel does via the pushViewController method invocation; the view "knows" that it is proper protocol to politely ask your navigationController to push a view, since the viewController conforms to the navigationController protocol. While you can create your own protocol, just using Gabriel's example and re-using the UINavigationController protocol is just fine.
The simplest do while loop for finding the viewController.
Swift 4
(more concise than the other answers)
My use case for which I need to access the view first
UIViewController
: I have an object that wraps aroundAVPlayer
/AVPlayerViewController
and I want to provide a simpleshow(in view: UIView)
method that will embedAVPlayerViewController
intoview
. For that, I need to accessview
'sUIViewController
.Combining several already given answers, I'm shipping on it as well with my implementation:
The category is part of my ARC-enabled static library that I ship on every application I create. It's been tested several times and I didn't find any problems or leaks.
P.S.: You don't need to use a category like I did if the concerned view is a subclass of yours. In the latter case, just put the method in your subclass and you're good to go.
Even though this can technically be solved as pgb recommends, IMHO, this is a design flaw. The view should not need to be aware of the controller.
UIView
is a subclass ofUIResponder
.UIResponder
lays out the method-nextResponder
with an implementation that returnsnil
.UIView
overrides this method, as documented inUIResponder
(for some reason instead of inUIView
) as follows: if the view has a view controller, it is returned by-nextResponder
. If there is no view controller, the method will return the superview.Add this to your project and you're ready to roll.
Now
UIView
has a working method for returning the view controller.