Sarah Boo Sarah Boo - 5 months ago 6x
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

) before trying to access properties of an

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

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.


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() {

        // 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