Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through all UIButtons in my Swift view?

Tags:

xcode

ios

swift

How would I loop through all UIButtons in my view in Swift? I would want to set all the titles to "", but my for-loop in Swift is giving an error.

for btns in self.view as [UIButton] {
  // set the title to ""
}
like image 595
melwyn pawar Avatar asked Sep 07 '14 21:09

melwyn pawar


3 Answers

This code should work:

for view in self.view.subviews as [UIView] {
    if let btn = view as? UIButton {
        btn.setTitleForAllStates("")
    }
}

You need to iterate through the subViews array.

like image 83
Woodstock Avatar answered Oct 15 '22 09:10

Woodstock


Shortened and updated for Swift 3 & 4

for case let button as UIButton in self.view.subviews {
    button.setTitleForAllStates("")
}
like image 26
Benno Kress Avatar answered Oct 15 '22 09:10

Benno Kress


Looping over subview works, but it's sometimes a little ugly, and has other issues.

If you need to loop over some specific buttons, for example to add corner radius or change tint or background color, you can use an array of IBOutlets and then loop over that.

var buttons = [SkipBtn, AllowBtn]
for button in buttons as! [UIButton] {
    button.layer.cornerRadius = 5
}
like image 40
afterxleep Avatar answered Oct 15 '22 09:10

afterxleep