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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With