Search code examples
iosswiftiboutlet

Put multiple UILabels into an array


In my app I currently have 9 labels on my storyboard, each showing a different value. (The values are stored in an array). As far as I know, each label has to be connected from the storyboard to the viewcontroller file separately, which makes my code look like this:

@IBOutlet weak var xValue: UILabel!
@IBOutlet weak var yValue: UILabel!
@IBOutlet weak var zValue: UILabel!

@IBOutlet weak var maxXValue: UILabel!
@IBOutlet weak var maxYValue: UILabel!
@IBOutlet weak var maxZValue: UILabel!

@IBOutlet weak var minXValue: UILabel!
@IBOutlet weak var minYValue: UILabel!
@IBOutlet weak var minZValue: UILabel!

And to set the values, I need to manually do:

xValue.text = arr[0]
yValue.text = arr[1]
...
minYValue = arr[7]
minZValue = arr[8]

Is there a way to connect multiple labels from the storyboard into an array so that I can simply do something like:

for i in 0...8 {
    labelArray[i] = arr[i]
}

Solution

  • As rmaddy mentioned in a comment you can use an outlet collection:

    @IBOutlet private var labels: [UILabel]!
    

    Then in your storyboard labels will show up under Outlet Collections when right-clicking your ViewController, and you can link multiple labels:

    enter image description here