0

I have these outlets...

@IBOutlet weak var pill1: UIImageView!
@IBOutlet weak var pill2: UIImageView!
@IBOutlet weak var pill3: UIImageView!
@IBOutlet weak var pill4: UIImageView!
@IBOutlet weak var pill5: UIImageView!
@IBOutlet weak var pill6: UIImageView!
@IBOutlet weak var pill7: UIImageView!
@IBOutlet weak var pill8: UIImageView!
@IBOutlet weak var pill9: UIImageView!
@IBOutlet weak var pill10: UIImageView!

I need to hide all of them in the 'viewDidLoad' function. For example...

self.pill1.isHidden = true
self.pill2.isHidden = true
self.pill3.isHidden = true
etc... 
etc....all the way to...
self.pill10.isHidden = true

But instead of writing repetitive lines 10s of times that are very similar, how do I use a 'for loop', or whatever is needed, to make it more cleaner.

For example,

for index in 1...10 {

   pill(insert index here somehow).isHidden = true

}

I tried a few different ways, but I was getting errors with string types etc. I am new to this all. Any help appreciated. thank you

koz
  • 195
  • 1
  • 13

1 Answers1

0

You can put the views into an array like this:

for pill in [pill1, pill2, pill3, pill4, pill5, pill6, pill7, pill8, pill9, pill10] {
    pill.isHidden = true
}

You could consider using an @IBOutlet collection. In that case, all of your outlets would be wired to the same collection (array) variable:

@IBOutlet var pills: [UIImageView]!

for pill in pills {
    pill.isHidden = true
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • thanks. what about the word 'pill'? That is repetitive. Isn't there a way just to add different numbers to the end of it, and keep the 'pill' within the curly brackets? – koz Nov 04 '16 at 02:15
  • as in getting rid of the repetitive 'pill' written over and over in the square brackets. – koz Nov 04 '16 at 02:17
  • The names inside of the array literal `[ ]` have to match the names defined in your `@IBOutlet`s. You could use an `@IBOutlet` collection which is just an array that holds the outlets. That works if you don't care about the order of the items in the array. – vacawama Nov 04 '16 at 02:19