Created
March 30, 2016 16:02
-
-
Save codelynx/184332a83f13ebb7df49a5cacf6c935d to your computer and use it in GitHub Desktop.
UIView extension to find a specific UIViewController type in responder chain. And UIView extension to find specific UIView subclass in view hierarchy toward superview.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // UIView+Find.swift | |
| // | |
| // Copyright (c) 2016 Kaz Yoshikawa. Released under MIT License. | |
| extension UIView { | |
| func findViewController<T: UIViewController>() -> T? { | |
| var responder = self.nextResponder() | |
| while responder != nil { | |
| if let viewController = responder as? T { | |
| return viewController | |
| } | |
| responder = responder!.nextResponder() | |
| } | |
| return nil | |
| } | |
| func findView<T: UIView>() -> T? { | |
| var view = self.superview | |
| while view != nil { | |
| if let view = view as? T { | |
| return view | |
| } | |
| view = view!.superview | |
| } | |
| return nil | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
let myViewController = view.findViewController() as? MyViewControllerlet myView = view.findView() as? MyViewArticle about this code:
http://qiita.com/codelynx/items/d77f991aa5fb07374ef7
in Japanese