【问题标题】:How to iterate through multiple UILabels如何遍历多个 UILabel
【发布时间】:2017-06-05 21:12:52
【问题描述】:

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

这段代码说明了我想要做什么(虽然它很长而且重复)

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

【问题讨论】:

    标签: arrays swift loops


    【解决方案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"
        }
    }
    

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

    【讨论】:

      【解决方案2】:

      您可以通过将标签放入数组中并按以下方式遍历它们来做到这一点:

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

      祝你好运!

      【讨论】:

        猜你喜欢
        • 2016-02-08
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 2013-07-06
        • 2021-11-26
        • 2021-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多