3

When using the storyboard, you can draw 2 buttons onto it, and add then add them to an array by creating:

@IBOutlet private var cardButtons: [UIButton]!

This outlet collection is now an array of both buttons that loads before viewDidLoad as a variable.

How do I create this array of buttons programmatically without using storyboard?

I've tried this but it gives me a declaration error:

class ViewController: UIViewController {
    var cardButtons = [CardView]()
    let cardOne = CardView()
    cardButtons.append(cardOne)

    ...rest of viewController standard class
}
1
  • Use a singleton and load them through AppDelegate. Commented Dec 31, 2017 at 11:07

2 Answers 2

1

There a several points of time in the ViewController's lifecycle where you might want to fill the cardButtons array. For example you could do this in viewDidLoad.

class ViewController: UIViewController {
    var cardButtons = [CardView]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let cardOne = CardView()
        cardButtons.append(cardOne)
    }
}

Keep in mind that viewDidLoad is called every time the View is loaded into memory. In my example cardOne would be recreated every time. To avoid this you could store cardOne in a instance var, as you did initially.

class ViewController: UIViewController {
    var cardButtons = [CardView]()
    let cardOne = CardView()

    override func viewDidLoad() {
        super.viewDidLoad()
        cardButtons.append(cardOne)
    }
}

As I said, there several points of time in the ViewController's lifecycle where you might want to fill the cardButtons array. Other functions could be:

  • viewDidAppear(), to fill the area every time the view appears.
  • init(), if you are not using storyboard at all.
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect thanks - I ended up doing it slightly different than suggested, but this helped me a lot!
0

Here is what I ended up doing:

class ViewController: UIViewController {
    let uiView: UI = {
        var ui:UI = UI()
        let cardOne = CardView()
        let cardTwo = CardView()
        ui.addButton(item: cardOne)
        ui.addButton(item: cardTwo)
        return ui
    }()
...rest of viewController standard class
}

class UI {
    var cardButtons = [CardView]()

    func addButton(button: CardView){
        cardButtons.append(button)
    }
}

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.