2017-06-05 113 views
1

我要寻找一个优雅方式,通过数组迭代和它的每一个值分配给一个或多个五UILabel小号如何通过多个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" 
    } 

回答

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

你可以做的是把你的标签在一个数组和遍历它们以下列方式:

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

祝你好运!