It is easy to get view from VC, but in some cases we need to get VC from view reverse.
But on some special occasions, the Cocoa Library helps us to be thoughtful, such as when customizing the View transition Animation:
funcanimateTransition(transitionContextUIViewControllerContextTransitioning{}
When the system callbacks our Animatetransition method, it passes in a context parameter, from which we can easily get the toview,fromview that participate in the animation and their corresponding VC:
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
But not all situations will help you think so thoughtful, so sometimes you need to find its VC from the view, the online obj-c code example:
-(uiviewcontroller *) Viewcontroller {for (uiview * next = [ Span class= "Hljs-keyword" >self Superview]; next ; next = next . Superview) {uiresponder *nextresponder = [next Nextresponder]; if ([Nextresponder iskindofclass: [uiviewcontroller class ] ") { return (uiviewcontroller *) Nextresponder; }} return nil ;}
Let's change it to the swift version, here's the first attempt:
func Controller (view: UIView )->uiviewcontroller ? {for var next: UIView ? = view; next ! = nil ; next = next !. superview{if let Nextresponder = next ?. Nextresponder () where Nextresponder.iskindofclass (uiviewcontroller . self ) {return (nextresponder as! uiviewcontroller )}} return nil }
The method above can do its job well, but the compiler has a warning that the syntax for this will be removed in a future swift version, so we'll turn it into a code without warning:
func controller2(view:UIView)->UIViewController?{ next:UIView? = view repeat{ ifnext?.nextResponder() where nextResponder.isKindOfClass(UIViewController.self){ return (nextResponder as! UIViewController) } nextnext?.superview }whilenextnil returnnil }
As you can see, there is no warning, but the code is a little bit more.
Finally, we can replace the starting code with the following:
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!let toVC = controller2(toView)!let fromVC = controller2(fromView)!
How Swift obtains the Viewcontroller that the view belongs to