Girithsirion
Girithsirion

Reputation: 5

How can I create a function for multiple labels in a stack?

I have 3 labels and I want to generate random numbers for each of them. I use GKRandomSource class in function, thats ok. The problem is, if I want to have much more labels (ie. 30) and all with same action, I need to reference all labels one by one to IBAction, I need to state all labels one by one in func code… I’ve been searching for a shorter way, maybe put them all in 3 stacks (10 labels for each stacks) and trigger, but I got nothing. I tried outlet collections (as we use in UIButtons) but it doesn’t let me to change label text.

How can I use a function for multiple labels with no-repeat?

Example;

let allNumbers = [Int](1...99)
var shuffledNum = [Int]()

@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var labelTwo: UILabel!
@IBOutlet weak var labelThree: UILabel!

func generateNumbers() {
    shuffledNum = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: allNumbers) as! [Int]

    let threeNumbers = shuffledNum.prefix(3).sorted()

    labelOne.text = String(threeNumbers[0])
    labelTwo.text = String(threeNumbers[1])
    labelThree.text = String(threeNumbers[2])
}

Upvotes: 0

Views: 714

Answers (1)

sanjaykmwt
sanjaykmwt

Reputation: 605

you can make the array of UILabel's and put all the outlets in the same array then you can use for loop to do operations on each of them.

for example:

  @IBOutlet var formLabels: [UILabel]!

and can do as:

  formLabels.forEach { label in
  label.text = ""//put your random number function here
}

see its working after adding both outlets I have also shown the connection in the storyboard the connection exists

enter image description here

Upvotes: 1

Related Questions