Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

theprizerevealed

macrumors regular
Original poster
Feb 26, 2016
183
12
Is there some way to assign labels to buttons without writing each button names programmatically.

Let's say you have an array:

Code:
 array: [String] = ["cat", "dog", "mouse", "beaver"]

and you have four buttons, ButtonOne, ButtonTwo, ButtonThree, ButtonFour

is there someway to assign each value of an array to each of the four buttons without actually typing out

Code:
ButtonOne.setTitle(array[0])
ButtonTwo.setTitle(array[1])

et cetera

through a control loop?
 

casperes1996

macrumors 604
Jan 26, 2014
7,518
5,685
Horsens, Denmark
I mean yes; But it depends how you've access to the buttons.

Obviously if you have all the buttons in an array you can just go:

for b in buttons.indices {
buttons.text = array
}

or with setTitle if you prefer.

Otherwise, if the buttons come from InterfaceBuilder and you've assigned tags to them in IB you can use the view.getView(tag:) or whatever that method is called with a range loop.

Or if all the buttons are individual references but have similar naming structure like button1 button2 button3 you can use reflection I guess to get all the child variables of the class/struct and run through them with the Mirror struct.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.