Swift: Get all subviews of a specific type and add to an array
The filter
function using the is
operator can filter items of a specific class.
let myViews = view.subviews.filter{$0 is MyButtonClass}
MyButtonClass
is the custom class to be filtered for.
To filter and cast the view to the custom type use compactMap
let myViews = view.subviews.compactMap{$0 as? MyButtonClass}
Here you go
extension UIView { /** This is the function to get subViews of a view of a particular type */ func subViews<T : UIView>(type : T.Type) -> [T]{ var all = [T]() for view in self.subviews { if let aView = view as? T{ all.append(aView) } } return all }/** This is a function to get subViews of a particular type from view recursively. It would look recursively in all subviews and return back the subviews of the type T */ func allSubViewsOf<T : UIView>(type : T.Type) -> [T]{ var all = [T]() func getSubview(view: UIView) { if let aView = view as? T{ all.append(aView) } guard view.subviews.count>0 else { return } view.subviews.forEach{ getSubview(view: $0) } } getSubview(view: self) return all } }
You can call it like
let allSubviews = view.allSubViewsOf(type: UIView.self)let allLabels = view.allSubViewsOf(type: UILabel.self)
To do this recursively (I.e. fetching all subview's views aswell), you can use this generic function:
private func getSubviewsOf<T : UIView>(view:UIView) -> [T] { var subviews = [T]() for subview in view.subviews { subviews += getSubviewsOf(view: subview) as [T] if let subview = subview as? T { subviews.append(subview) } } return subviews}
To fetch all UILabel's in a view hierarchy, just do this:
let allLabels : [UILabel] = getSubviewsOf(view: theView)