Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: calling function from another viewcontroller makes objects nil

Tags:

ios

swift

I have two simple ViewController: the first one has a IBOutlet linked to a UIImageView and a function that sets the image alpha channel. The second controller has a button that, when it's trigged, should call the function to set the alpha channel.

Here my code:

class FirstViewController: UIViewController {

     @IBOutlet imageView: UIImageView! 

     func changeAlphaChannel() {
         imageView.alpha = 0.5
     }
}

class SecondViewController: UIViewController {

     let firstController = FirstViewController()

     @IBAction func buttonPressed(sender: UIButton) {
         firstController.changeAlphaChannel()
     }
}

Calling changeAlphaChannel() inside FirstViewController works as aspected, but if I call it pressing the button, imageView becomes nil and the app crashes. How can I fix this? Thanks

like image 659
johnnyparafango Avatar asked Jan 30 '16 16:01

johnnyparafango


2 Answers

Its crashing because your imageView is nil. Just initialising firstController with FirstViewController() will not do. You'll have to load that view controller from storyboard. You can do it this way

let storyboard: UIStoryboard = UIStoryboard.init(name: "StoryboardName", bundle: nil)
let firstViewController: FirstViewController = storyboard.instantiateViewControllerWithIdentifier("StoryboardIdentifier") as! FirstViewController

UPDATE

Now IBOutlets of firstViewController will be set only when firstViewController's view is instantiated, which in your case is not happening. What you have to do is first display view of firstViewController and then call your function.

like image 180
Vishnu gondlekar Avatar answered Nov 27 '22 00:11

Vishnu gondlekar


You're not calling the function on the first controller - you're creating a new instance of the first controller, which doesn't have anything set in the image.

You need to pass a reference to the first controller through to the second.

like image 36
Russell Avatar answered Nov 27 '22 00:11

Russell