如何遍历多个UILabel

时间:2017-06-05 21:12:53

标签: arrays swift loops

我正在寻找一种优雅的方式来遍历数组并将其每个值分配给五个UILabel中的一个或多个

这段代码说明了我要做的事情(尽管它很长且重复)

    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"
    }

2 个答案:

答案 0 :(得分:1)

您可以将标签放在另一个数组中并迭代它们:

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"
    }
}

这样您就可以对冗余代码进行分组

答案 1 :(得分:1)

您可以通过将标签放在数组中并按以下方式迭代它们来实现:

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"
    }
}
祝你好运!