Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively find a view of a specific type iOS

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.

like image 779
Avinash Sharma Avatar asked Jan 19 '26 13:01

Avinash Sharma


1 Answers

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)
like image 61
RajeshKumar R Avatar answered Jan 22 '26 18:01

RajeshKumar R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!