Created
June 10, 2019 19:47
-
-
Save DanielCardonaRojas/a795633295184fffcbfc1925e9192cb7 to your computer and use it in GitHub Desktop.
Query the subview hierarchy
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 { | |
func allSubviews<T: UIView>(of type: T.Type) -> [T] { | |
let directSubviews = subviews.compactMap({ $0 as? T }) | |
var nested = [T]() | |
for s in subviews { | |
let ss = s.allSubviews(of: type) | |
nested += ss | |
} | |
return directSubviews + nested | |
} | |
func firstSubview<T: UIView>(of type: T.Type) -> T? { | |
if let directSubview = subviews.first(where: { $0 is T}) as? T { | |
return directSubview | |
} | |
for s in subviews { | |
guard let ss = s.firstSubview(of: type) else { | |
continue | |
} | |
return ss | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment