I have a UIView I want to parse all the subviews of the view and return the instance of subview that is of type CustomClass
With view.subviews I only get to immediate subviews , I want to parse all subviews and return my subview that matches a condition.
findView(key : uniqueKey , view : UIView)
for subview in view.subviews {
if subview.uniqueKey == key
return subview // and break
else
continue with recursively searching
}
I know I need to solve this recursively but I am sure that only one instance of this view is present so as soon as I find the instance I would want to return and break the recursion.
How can I achieve the same.
You can use this generic UIView extension method to find any object of specific class. It returns nil if no subview exists of that class.
extension UIView {
func find<T:UIView>(_ ofType:T.Type) -> T? {
if let test = subviews.first(where: { $0 is T }) as? T {
return test
} else {
for view in subviews {
return view.find(ofType)
}
}
return nil
}
}
Usage
let firstBtn = self.view.find(UIButton.self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With