2017-06-05 47 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" 
    } 
} 

祝你好運!