Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Access button from another view controller

Let's say I have a firstViewController and a secondViewController. The first one contains a firstButton and the second one - a secondButton. Here's what I want to do: when user clicks the secondButton, some firstButton's property changes.

Unfortunately, when I create an instance of a firstViewController in a secondViewController and then trying to access a firstButton, I get an error:

"fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"

So, technically, I'm trying to do this as follows:

var ins = firstViewController()

@IBAction func secondButtonisPressed(){ ins.firstButton.alpha = 0 }

What is the proper way to implement that?

Thanks in advance.

1 Answer

Hey Anton! One design pattern to accomplish this is with custom delegation. You can read about it in the Apple documentation here or see an example on StackOverflow (under Passing Data Back, on the first response). Unfortunately, it's not something you can implement with a single line of code, but it is a really powerful design pattern that you will see over and over again as you continue iOS development! (Please feel free to ask follow-up questions if you want help implementing it for your project!)