Last active
July 24, 2019 15:49
-
-
Save sgbasaraner/ab8cc181569fd537254de7c3abab1ca1 to your computer and use it in GitHub Desktop.
Find a subview that satisfies a predicate recursively
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
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