skip to Main Content

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?

3

Answers


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

    Login or Signup to reply.
  2. It would help if you were sure before using .selected. Have you set the title for the selected state of the button.

    guard let buttonTitle = sender.titleLabel?.text else {
        return
    }
    let text = "(buttonTitle) button pressed"
    out.text = text
    

    *Updated code

    Login or Signup to reply.
  3. I am learning ios development. According to my tutorial…

    That’s the problem: your tutorial is too old. What it says is not how things work nowadays. If you don’t want to learn how things work now, then change the button style to Default in the storyboard to move the button behavior into the past, like your tutorial, and then your code will work as you expect.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search