Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a 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.

like image 489
Ivan Panshin Avatar asked Sep 26 '22 01:09

Ivan Panshin


1 Answers

Your problem here is that the IBOutlets of your firstViewController are only available (!= nil) after the viewDidLoad() firstViewController's method has being called.

In other words, you have to present the view, before you can make any changes to a UIViewController IBOutlet.

How you can solve this?

Add a variable into FirstViewController that works as a flag for you.

for example: var hideFirstButton = false

in the viewDidLoad or viewWillAppear method of FirstViewController check for hideFirstButton's value and hide or show your firstButton.

Then, before you present your FirstViewController change the value of hideFirstButton to the needed for your application to run fine.

UPDATE:

Other workaround, using Storyboard is (This approach has the inconvenient that the completion handler is called after viewWillAppear() so the button is visible for a second):

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let firstViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
    self.presentViewController(firstViewController, animated: true, completion: {
        //This lines will be called after the view is loaded so the code will run
        firstViewController.firstButton.alpha = 0
    })

EXAMPLE: an example at GitHub

like image 97
Hugo Alonso Avatar answered Nov 15 '22 13:11

Hugo Alonso