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
}
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With