Is it possible to set, for instance, .isHidden to multiple buttons at once, instead of:
button1.isHidden = true
button2.isHidden = true
button3.isHidden = true
Something like: button1, button2, button3.isHidden = true.
You can also create Array extension. It also make more sense to constraint element type to UIButton, such that you can't call it for any other type of array.
Something like this,
extension Array where Element == UIView {
func show() {
forEach { $0.isHidden = false }
}
func hide() {
forEach { $0.isHidden = true }
}
}
Then, using it like so,
[button1, button2, button3].hide() // hide buttons
[button1, button2, button3].show() // show
Extending collection makes more sense in this case, which gives more flexibility as the hide / show could be used with ArraySlices then.
Here is how you would do this,
extension Collection where Element: UIView {
func show() {
forEach { $0.isHidden = false }
}
func hide() {
forEach { $0.isHidden = true }
}
func toggleVisibility() {
forEach { $0.isHidden = !$0.isHidden }
}
}
And with this you can do some cool thing like,
// hide all but not first
myArrayOfButtons.dropFirst().hide()
// hide buttons in indexes 0 to 1
myArrayOfButtons[0 ... 1].hide()
// show all buttons but not last
myArrayOfButtons.dropLast().show()
// hide first 2 buttons
myArrayOfButtons.prefix(2).hide()
// show last button
myArrayOfButtons.suffix(1).show()
// toggle visibility of first 2
myArrayOfButtons.prefix(2).toggleVisibility()
In addition to @ukim's answer, you can use an Outlet Collection.
In you storyboard, drag from your first button and select Outlet Collection rather than Outlet as you would normally do.

Which gives you…
@IBOutlet var buttons: [UIButton]!
Then connect all your other buttons to the same @IBOutlet
You can then say
buttons.forEach {
$0.isHidden = true
}
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