Home > Mobile >  can not get title from my button by using sender.title(for: .selected)
can not get title from my button by using sender.title(for: .selected)

Time:06-09

I am learning ios development. According to my tutorial, I have code as below for making a button reflection demo.

import UIKit

class ViewController: UIViewController {

    @IBAction func buttonPressed(_ sender: UIButton) {
        let title = sender.title(for: .selected)!
        let text = "\(title) buttion pressed"
        out.text = text
    }
    

    @IBOutlet weak var out: UILabel!
    
}

After I click the button in the simulator, I got an error.

Unexpectedly found nil while unwrapping an Optional value

let title = sender.title(for: .selected)! causes this error. My Xcode version is 13.4.

I have associated the button with the method correctly by dragging it.

My button has title names 'left' by double_clicking it and inputing the data left in Storyboard.

If I delete the ! of let title = sender.title(for: .selected)!, my label can show nil button pressed.It is seems that IBOutlet can works fine.

Is there any point I missed for getting the title of my button?

CodePudding user response:

You have to connect your IBOutlet to the storyboard. I have used your code and it's working fine. Please check the attached screenshot.enter image description here

  • Related