Change @IBOutlet properties of a bunch of UIImageView all at once

Hi all,

I'm recently became an enrolled developer, mainly for learning and fun.

I'm trying to learn studying online and by doing iOS apps but sometime I got stuck and I cannot find answers anywhere.

Maybe it's a silly question and if that's the case please forgive me to have wasted your precious time, but if it's not please can someone explain to me how to do this?


I have a bunch of UIImageViews outlets (36 to be exact, arranged in a grid of 6x6 squares) and I would like to know if there's a way to do something like this:


@IBOutlet weak var quadrato01: UIImageView!
....
....
....
....
 @IBOutlet weak var quadrato36: UIImageView!


let numero = 08


quadrato(numero).backgroundColor = UIColor.red

I know that is terribly wrong but I didn't know how to explain to you. The numero constant is only for explaining that somewhere in the code I have a number that I would like to attach at the end of the quadratoXX name outlet to acces its properties.

Sorry if I'm not explaining clearly but I'm not English speaking


Thanks in advance for any help and feel free to ask me other info if I was not clear enough

Accepted Reply

Looks like you need to use an IBOutletCollection


    @IBOutlet var quadratos: [UIImageView]!


Then connect all the 6 to the same (take care to do it in right order)


Then call

quadratos(numero).backgroundColor = UIColor.red


It could be wise to set, in IB, the tag of each UIImageView from 1 to 36

Then you could test like this:


for quadrato in quadratos where quadrato.tag == numero {
     quadrato.backgroundColor = UIColor.red
}

Replies

Looks like you need to use an IBOutletCollection


    @IBOutlet var quadratos: [UIImageView]!


Then connect all the 6 to the same (take care to do it in right order)


Then call

quadratos(numero).backgroundColor = UIColor.red


It could be wise to set, in IB, the tag of each UIImageView from 1 to 36

Then you could test like this:


for quadrato in quadratos where quadrato.tag == numero {
     quadrato.backgroundColor = UIColor.red
}

Thank you so much. I'll try ASAP


BTW: I've always asked myself what @IBOutletCollection was 😁

It works! Thanks again.


P.S: The only problem was that you wrote "numero" between parenthesis instead of square brackets. It took me a little while to figure out that IBOutlet collections are just an array of outlets 🙂

Sorry, I copied your line 12 of original post and did not notice in forum editor it was parenthesis and not brackets.


But you corrected by yourself, great.


Wish you good continuation.

Thanks, you were so kind.

BTW thanks to you I've almost finished my first game. I've posted a question about bonus views like that on commercial games because i would like to integrate it in mine to make it more appealing.

The goal is to upload it on the Apple Store.

That would be amazing 🙂