Marmelador
Marmelador

Reputation: 1017

How to iterate through multiple UILabels

I am looking for an elegant way to iterate through an array and assign each of its values to one or more of five UILabels

This code illustrates what I am trying to do (although it is very long and repetitive)

    if touches.count >= 1 {
        positionTouch1LBL.text = String(describing: touches[0].location(in: view))
    } else {
        positionTouch1LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 2 {
        positionTouch2LBL.text = String(describing: touches[1].location(in: view))
    } else {
        positionTouch2LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 3 {
        positionTouch3LBL.text = String(describing: touches[2].location(in: view))
    } else {
        positionTouch3LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 4 {
        positionTouch4LBL.text = String(describing: touches[3].location(in: view))
    } else {
        positionTouch4LBL.text = "0.0 / 0.0"
    }

    if touches.count >= 5 {
        positionTouch5LBL.text = String(describing: touches[4].location(in: view))
    } else {
        positionTouch5LBL.text = "0.0 / 0.0"
    }

Upvotes: 1

Views: 195

Answers (2)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

You could do that by putting your labels in an array and iterate through them in the following way:

let labelsArray = [UILabel(), UILabel(), ... ] // An array containing your labels

for (index, element) in labelsArray.enumerated() {
    if index < touches.count {
        element.text = String(describing: touches[index].location(in: view))
    } else {
        element.text = "0.0 / 0.0"
    }
}

Good luck!

Upvotes: 1

Christian Ascone
Christian Ascone

Reputation: 1177

You could put your labels inside another array and iterate through them:

let labelsArray = [positionTouch1LBL, positionTouch2LBL, positionTouch3LBL, positionTouch4BL, positionTouch5LBL]

for i in 0..<labelsArray.count {
    // Get i-th UILabel
    let label = labelsArray[i]
    if touches.count >= (i+1) {
        label.text = String(describing: touches[i].location(in: view))
    }else{
        label.text = "0.0 / 0.0"
    }
}

This way you are able to group redundant code

Upvotes: 1

Related Questions