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-08

I am learning ios development. According to my tutorial, I have code as below for making a buttion 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 buttion 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. Is there any point I missed? My button has title names 'left' by double_clicking it and inputing the data left in Storyboard .

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.Image

CodePudding user response:

It would help if you were sure before using .selected. Have you set the title for the selected state of the button.

If not, you need to use .normal to get the button title.

guard let buttonTitle = sender.title(for: .normal) else {
    return
}
let text = "\(buttonTitle) button pressed"
out.text = text
  • Related