Skip to content

Instantly share code, notes, and snippets.

@myell0w
Created June 13, 2018 12:05
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save myell0w/7484c3253e33425ed35a6579d088afb6 to your computer and use it in GitHub Desktop.
Save myell0w/7484c3253e33425ed35a6579d088afb6 to your computer and use it in GitHub Desktop.
Traverse View Hierarchy Upwards
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
}
}
@nkukushkin
Copy link

nkukushkin commented Jun 13, 2018

Isn't it a little imprecise that this method can return the view it was called on, when the name explicitly says "superview"?

@e28eta
Copy link

e28eta commented Jun 13, 2018

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