How do I access an outlet from another View Controller? (Swift)

407 views Asked by At

I am new to Swift programming and am trying to make a simple app that presents a Challenge which you can then complete by pressing a button. Then in a separate view controller you unlock images when you have completed a certain number of challenges.

In the Home View controller there is a button that when pressed increases my count variable by one. Basically I want to check and see if that count is above a certain number and if it is I want to allow the image to be seen.

Here is my check for badges function:

func checkBadges() {
        let vc = AccomplishmentsViewController(nibName: "AccomplishmentsViewController", bundle: nil)
        if count >= 3 {
            print("Bronze Trophy should be showing")
            vc.bronzeTrophy.isHidden = false
        }
    }

The problem is that I get an error, "Unexpectedly found nil while implicitly unwrapping an Optional value". I have tried a ton of different things to work around this, but have been unsuccessful. Any help would be greatly appreciated. Thanks!

For reference here is my other view controller:

class AccomplishmentsViewController: UIViewController {

    @IBOutlet var bronzeTrophy: UIImageView!

}
1

There are 1 answers

0
Duncan C On BEST ANSWER

Short answer: Don't do that. You should treat a view controller's views as private.

If you mess with another view controller's views you are violating the principle of encapsulation. One module should not depend on the implementation details of another module.

Instead, add a Bool function showTrophy(_ show: Bool).

Keep a pointer to the other view controller (don't create a new instance, as aheze points out.)

In your AccomplishmentsViewController's showTrophy method set the visibility of your trophy icon appropriately.