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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments