Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Created June 10, 2019 19:47
Show Gist options
  • Save DanielCardonaRojas/a795633295184fffcbfc1925e9192cb7 to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/a795633295184fffcbfc1925e9192cb7 to your computer and use it in GitHub Desktop.
Query the subview hierarchy
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