Skip to content

Instantly share code, notes, and snippets.

@sgbasaraner
Last active July 24, 2019 15:49
Show Gist options
  • Save sgbasaraner/ab8cc181569fd537254de7c3abab1ca1 to your computer and use it in GitHub Desktop.
Save sgbasaraner/ab8cc181569fd537254de7c3abab1ca1 to your computer and use it in GitHub Desktop.
Find a subview that satisfies a predicate recursively
extension UIView {
/// Traverses subviews recursively with breadth first search, returns the first subview that
/// satisfies the predicate.
func firstSubview(where predicate: (UIView) -> Bool) -> UIView? {
var subviewsToTraverse = subviews
while subviewsToTraverse.count > 0 {
guard !predicate(subviewsToTraverse[0]) else {
return subviewsToTraverse[0]
}
subviewsToTraverse.append(contentsOf: subviewsToTraverse[0].subviews)
subviewsToTraverse.remove(at: 0)
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment