Created
June 13, 2018 12:05
-
-
Save myell0w/7484c3253e33425ed35a6579d088afb6 to your computer and use it in GitHub Desktop.
Traverse View Hierarchy Upwards
This file contains 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
extension UIView { | |
func findFirstSuperview<T>(ofClass viewClass: T.Type, where predicate: (T) -> Bool) -> T? where T: UIView { | |
var view: UIView? = self | |
while view != nil { | |
if let typedView = view as? T, predicate(typedView) { | |
break | |
} | |
view = view?.superview | |
} | |
return view as? T | |
} | |
} |
Neat. You can leave out the ofClass viewClass: T.Type
:
func findFirstSuperview<T>(where predicate: (T) -> Bool) -> T? where T: UIView {
and just supply the type in the predicate:
foo.findFirstSuperview { (v: UIScrollView) -> Bool in
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Isn't it a little imprecise that this method can return the view it was called on, when the name explicitly says "superview"?