2015-05-10 39 views
-1

我在Swift中編程,我想在單個循環中設置幾個變量。 這些是UIButtons,它們都需要相同的設置。但我不知道如何使用「我」來引用這些變量。這是我的嘗試:如何在FOR循環中設置多個變量?

var gg1:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton 
var gg2:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton 
var gg3:UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton 

//further in the code 
for i in 1...3 { 
    gg(i).layer.anchorPoint.x = 0 
    gg(i).titleLabel?.font = UIFont(name: "Arial", size: 20*rightFontSize) 
    gg(i).setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal) 
    gg(i).sizeToFit() 
    gg(i).center = CGPointMake(w/20,11*h/10) 
    scrollView.addSubview(gg(i)) 
} 
+1

將它們放在數組中。 – mustafa

回答

1

的按鈕需要在一個陣列,例如:

let buttons = [gg1, gg2, gg3] 

然後,您可以使用一個for循環,像這樣:

for button in buttons { 
    // Setup the button... 
    scrollView.addSubview(button) 
} 

或者,稍微縮短一點:

for button in [gg1, gg2, gg3] { /* Setup */ } 

或者,如果按鈕都被初始化以同樣的方式(你需要按鈕的數組),你可以這樣做:

var buttons: [UIButton] = [] 
for i in 0..<3 { 
    let button = UIButton.buttonWithType(UIButtonType.System) as! UIButton 
    // Setup the button... 
    buttons.append(button) 
    scrollView.addSubview(button) 
} 
1

您可以創建按鈕的排列:

let array = [gg1, gg2, gg2] 

for i in array.count 
{ 
    //do something 
    array[i] 
} 
+0

謝謝!它完美的作品:) –

+0

如果答案解決了你的問題,你應該考慮考慮它。 – ABakerSmith

0

你可以做很好:

[gg1,gg2,gg3].map({(button:UIButton) -> UIButton in  
    // Configure the buttons 
    return button 
})