Get ALL view inside ViewController

Viewed 3262

I am trying to get all views inside my UIViewController.

I am using this code:

    for subview : UIView in self.view.subviews{
        //code here
    }

the problem is that I don't get views that are inside a UIView. so I get all view except of their children.

please, how can I get ALL Views that are either child or parent inside my UIViewController? even if a view has a child that has a child that has a child. I want to go through all views.

thanx in advance :)

(please in swift 4.0)

3 Answers

You need to recursively process all subviews.

func processSubviews(of view: UIView) {
    // 1. code here do something with view
    for subview in view.subviews {
        // 2. code here do something with subview
        processSubviews(of: subview)
        // 3. code here do something with subview
    }
    // 4. code here do something with view
}

You need to put your code at either position 1, 2, 3, or 4 (or possibly two or more of those places) depending on the results you want.

Then you can call this as:

processSubviews(of: self.view)

For get all views (as Label, Button, View, ...) in your view hierarchy and access to all child view in your viewController you should using from a recursive func to iterate all views :

func getAllSubviews(view:UIView) {
    for subview in view.subviews {
        if let takenLabel = subview as? UILabel {
            takenLabel.backgroundColor = UIColor.red
        }
        getAllSubviews(view:subview)
    }
}

You can using from this func to access other view like button and change them .

in this case i'm changing background color of all label in viewController to red

There are many different way to get subviews

To Get all the subviews in the parent view

for subview in view.subviews{

      // you can get all of your views one by one here.
}

To Filter if any tagged view is available or not (lets assume view is tagged by 100)

        view.subviews.filter{$0.tag == 100}

Extensions to check if Any view contains sub views

extension UIView{

    func isAvailabletoParentView(inParentView : UIView, subViewTag : Int) -> Bool{

        var isAvailable = false

        for subviews in inParentView.subviews{

            if subviews.tag == subViewTag{

                isAvailable = true
                return true
            }else{

                isAvailable = false
            }
        }
        return isAvailable
    }
}

Call Extension like

subview.isAvailabletoParentView(inParentView: parentView, subViewTag: anyTagToSubView)

Hope it will helps , Happy coding .

Related