Search code examples
iosswiftuibuttonuikitoption-type

Add UIButtons to array on ViewDidLoad


I'm working through an example project.

I'm trying to count the number of UIButtons the ViewControllers view has, and then add them to an array, so that I can programatically access them i.e. change colour / title etc.

import UIKit

class ViewController: UIViewController
{
    var cardButtons: [UIButton]!

    let cardForegroundColour = UIColor.white
    let cardBackgroundColour = UIColor.orange

    lazy var game = ConcentrationGame(numberOfPairsOfCards: (self.cardButtons.count + 1) / 2)

    override func viewDidLoad()
    {
        for case let button as UIButton in self.view.subviews
        {
            button.backgroundColor = cardForegroundColour
            self.cardButtons.append(button)
        }

        print ("number of buttons /(self.cardButtons.count)")
    }

So, it builds fine, but crashes on the append line with:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Now, if I set a breakpoint, the button object is a valid object.

I can change all the colours fine, but I just can't add them to the array of cardButtons.

I know I can setup cardButtons as a Collection Outlet, and wire them up manually, but I want to be able to change the UI and the code just adapts, so adding more buttons, or removing some, doesn't change the code or require manual rewiring.

I realise the problem is with my understanding of optionals, but I thought that the ! at the beginning and the concrete object button was the right approach.


Solution

  • The Problem is that cardButtons is nil.

    Change this line var cardButtons: [UIButton]! to var cardButtons = [UIButton]()