Sarah Boo Sarah Boo - 6 months ago 9
Swift Question

Where to access IBOutlet var and use it to define a constant accessible to the class

I read that I should wait until the view loads (or

viewDidLoad()
) before trying to access properties of an
IBOutlet
.

My problem is: I want to store the title color property of an
IBOutlet
UIButton as a constant that is accessible to the entire ViewController class, or at least from an
IBAction
method within the class- but it seems that that is out of scope since I'm defining the constant inside
viewDidLoad()
and I am unable to access it anywhere else. I need to use it in both
viewDidLoad()
and in an
IBAction
method.

I can't define it outside of any class methods because I get an error saying
Instance member 'lowFilterButton' cannot be used on type ViewController
so what should I do? I could hardcode the colour into both methods but I want to find a better solution for future reference.

Answer

It looks like you are try to access a class constant in an instance method (viewDidLoad()) without the proper reference. Class constants belong to the class, not the instance so you can't write:

color = ...      // invalid
self.color = ... // invalid

Do this instead:

class ViewController: UIViewController {
    static var color: UIColor!
    @IBOutlet weak var myButton: UIButton!

    func viewDidLoad() {
        super.viewDidLoad()

        // Refer to the class of the current instance
        self.dynamicType.color = myButton.tintColor

        // You can also refer to the class by name
        ViewController.color = myButton.tintColor
    }
}
Comments