0
votes

I am trying to change the label text with the code below:

class ViewController: UIViewController {

    @IBAction func buttontobepressed(_sender: Any)
    {
       displayMessage.text?="button pressed"  
    }

    @IBOutlet  weak var displayMessage: UILabel!

when I try running it, it gives me an exception:

$ ibc++abi.dylib: terminating with uncaught exception of type NSException$

Full log:

2017-06-10 12:07:14.672 blabby[4334:781388] -[blabby.ViewController buttontobepressed:]: unrecognized selector sent to instance 0x7bf54fe0 2017-06-10 12:07:14.679 blabby[4334:781388] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[blabby.ViewController buttontobepressed:]: unrecognized selector sent to instance 0x7bf54fe0' libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) **

1
Remove the ? after the text property write it like displayMessage.text = "button pressed" - Nirav D
'NSInvalidArgumentException' is the error message show ...an uncaught exception. - Ashutosh Mane
Is your label outlet connected ? also add full error - Nirav D
**2017-06-10 12:07:14.672 blabby[4334:781388] -[blabby.ViewController buttontobepressed:]: unrecognized selector sent to instance 0x7bf54fe0 2017-06-10 12:07:14.679 blabby[4334:781388] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[blabby.ViewController buttontobepressed:]: unrecognized selector sent to instance 0x7bf54fe0' libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) ** - Ashutosh Mane
add the space between _ and sender like buttontobepressed(_ sender: Any) - Nirav D

1 Answers

0
votes

The correct way of using Any class inside a action method is to check the appropriate class always when performing action, see below.

@IBAction func buttontobepressed(_ sender: Any){

    // checking if sender is as object of UIButton class
    if sender is UIButton{
        self.displayMessage.text = "button pressed"    
    }
}

Note: for proper use of any UI component including UILabel inside your programm you must connect its IBOutlet using storyboard after declare, otherwise you will get the runtime error.