0

How can I iterate through objects/variables in Swift. Can I create an array or dictionary when I have objects attached so that I don't have to write code for each button. I'm a nubie so please speak to me like I'm four. Thanks for the help in advance.

import UIKit
class ViewController: UIViewController {

@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
...


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.button1.alpha = 0.0
    self.button2.alpha = 0.0
    self.button3.alpha = 0.0
    ...
}

2 Answers 2

3
import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!
    @IBOutlet weak var button3: UIButton!
    var arrayOfButtons = [UIButton]()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    arrayOfButtons = [button1, button2, button3]
    for button in arrayOfButtons {
        button.alpha = 0.0
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to add variable into an object name. For example: button/(count).alpha = 0.0
@codekid, I don't think you can add a variable like that once an object is created. But if you want to call a specific button, you could create a Dictionary [String: UIButton] instead of an array ["button1": button1, "button2": button2, "button3": button3]. Then call dictOfButtons["button/(count)"].alpha = 0.0.
1

In addition to Tim's answer, you can also create buttons programmatically, and deal with them in your code!

override func viewDidLoad() {
for i in 1...10 {
    let button = UIButton()
    button.frame = CGRectMake((CGFloat(i-1)*50), 0, 50, 50)
    button.targetForAction("buttonClick:", withSender: self)
    button.tag = i
    self.view.addSubview(button)
}
}


func buttonClick(sender:AnyObject) {
    let tag = sender.tag!
    //click logic here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.