Stanislav Marynych
Stanislav Marynych

Reputation: 198

Can't add a action to menu item

Why can't I add an action? When I push the button setDefault or the clearText (code in AppDelegate) pop up an error: My error

My story board:

Story Board

My menu items

My ViewController:

class ViewController: NSViewController {

    @IBOutlet weak var textField: NSTextField!
    @IBOutlet weak var Lable: NSTextField!


    @IBAction func setButton(_ sender: Any) {
        let value = textField.stringValue
        Lable.stringValue = value
    }

}

My AppDelegate :

    @IBAction func setDefault(_ sender: Any) {
        let defaultVar:String = "Default"
        Label.stringValue = defaultVar
    }

    @IBAction func clearText(_ sender: Any) {
        let clear:String = " "
        Label.stringValue = clear
    }

Upvotes: 0

Views: 246

Answers (2)

vadian
vadian

Reputation: 285270

Move both actions into the view controller, change the sender to NSMenuItem and adjust Lable (by the way please name properties with starting lowercase letter)

class ViewController: NSViewController {

    @IBOutlet weak var textField: NSTextField!
    @IBOutlet weak var Lable: NSTextField!


    @IBAction func setButton(_ sender: Any) {
        let value = textField.stringValue
        Lable.stringValue = value
    }

    @IBAction func setDefault(_ sender: NSMenuItem) {
        let defaultVar = "Default"
        Lable.stringValue = defaultVar
    }

    @IBAction func clearText(_ sender: NSMenuItem) {
        let clear = " "
        Lable.stringValue = clear
    }

}

Then in Interface Builder connect the menu items to First Responder (the red cube on the top) of AppDelegate and select the methods in the list respectively. The first controller in the responder chain which implemented one of the methods will respond to it.

Upvotes: 1

Francesco Destino
Francesco Destino

Reputation: 349

Try to debug the function when you get the error and see if Lable and Lable.stringValue has been setted; because the error "Unexpectedly found nil while unwrapping an Optional value" appears when your value is not setted, so the compiler found that as nil and it crash.

Anyway post a screenshot of your storyboard and more code in your ViewController so we can help you better

Upvotes: 0

Related Questions