-2

I'd like to do a label which is present only when button is touched. When function hidden() is called in MainViewController It's working well but when i'm calling it from ButtonAction class (same function) I get an classic error:

Unexpectedly found nil while unwrapping an Optional value

Here's the code:

//  MainViewController.swift

import UIKit

class MainViewController: UIViewController {

    @IBOutlet weak var labelToShow: UILabel!
    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        labelToShow.isHidden = true
    }

    func hidden() {
        labelToShow.isHidden = true
    }

    func inHidden() {
        labelToShow.isHidden = false
    }

}

AND :

//  ButtonAction.swift


import UIKit

class ButtonAction: UIButton {

    var touched:Bool = false
    var mainScreen = MainViewController()

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        sleep(1)
        mainScreen.hidden()
        touched = true
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        mainScreen.inHidden()
        touched = false
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
gfd
  • 37
  • 6
  • Can you show full code how you create ButtonAction class and ViewController ? – Grzegorz Krukowski Dec 16 '16 at 10:52
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – rmaddy Dec 16 '16 at 15:38

2 Answers2

1

The mainScreen instance created with the default initializer MainViewController() is different from those designed in Interface Builder.

You need the actual reference to the main view controller (via IBOutlet or protocol / delegate etc.)

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Well, it's not different, it just haven't been set up yet with `InterfaceBuilder` stuff, like setting values to `@IBOutlet`s and adding `@IBAction`s as targets, and other UI stuff like, fonts, colors, etc. All of that can be done in code too. – user28434'mstep Dec 16 '16 at 12:22
  • I've created protocol and "nil" problem still happend. I've tested protocol with example like print etc and everything was ok. – gfd Dec 22 '16 at 13:51
0

In that line of code you are creating a new instance of your MainViewController :

var mainScreen = MainViewController()

You have to get the reference of your MainViewController() instance (created automatically by storyboard)

Federico Malagoni
  • 722
  • 1
  • 7
  • 21