Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set values to multiple buttons or labels at once?

Tags:

swift

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.

like image 818
Anvil Avatar asked Aug 10 '18 20:08

Anvil


2 Answers

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()
like image 167
Sandeep Avatar answered Oct 11 '22 17:10

Sandeep


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.

enter image description here

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
}
like image 27
Ashley Mills Avatar answered Oct 11 '22 19:10

Ashley Mills