Alexey K
Alexey K

Reputation: 6723

Is It possible to iterate through objects on the view?

I have some buttons on the view. I don't know how many, I know that it can be minimum of 2 or maximum of 4. I want to check each button's title text and add to array true or false depending on value of title.

is it possible to do ?

Upvotes: 0

Views: 37

Answers (2)

Munahil
Munahil

Reputation: 2419

Yes, it is possible to iterate through all objects inside the view. To see all the subviews present in your view, you can do following:

    for view in self.view.subviews as! [UIView] {
    if let btn = view as? UIButton {
        if btn.title == "whateverYourCriteriaIs" { 
            //your code
        }
        else {
           //do something else
        }
    }
}

Upvotes: 1

Nilesh Patel
Nilesh Patel

Reputation: 6394

Try below thing..

    for view in self.view.subviews {
        if view.isKindOfClass(UIButton){
            // Add you logic over here. 
            // you can check the tag of button as well.
        }
    }

Upvotes: 1

Related Questions