Home > Enterprise >  How to get the current Title of a button in Swift?
How to get the current Title of a button in Swift?

Time:11-29

What am I doing wrong?

I get this error:

let letterString = sender.title(for: .normal)! // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

when I tried to get the title of a button in swift like below:

import UIKit

class ViewController: UIViewController {
    
    // My IBOutlets
    @IBOutlet var treeImageView: UIImageView!
    @IBOutlet var correctWordLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!
    
    // My Outlet Collection
    @IBOutlet var letterButtons: [UIButton]!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // Begin the round.
        newRound()
        
    }
    
    var listOfWords = ["estufa", "nevera", "computadora", "empanada", "chuleta", "camarones", "brincar", "correr", "caminar", "tigre", "jirafa", "mono", "kisseemmee", "Tampa", "Orlando"]
    let incorrectMovesAllowed = 7
    let totalWins = 0
    let totalLosses = 0
    
    
    // My IBActions
    @IBAction func letterButtonPressed(_ sender: UIButton) {
        sender.isEnabled = false


        let letterString = sender.title(for: .normal)!  // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value


        let letter = Character(letterString.lowercased())
        currentGame.playerGuessed(letter: letter)
        updateUI()
    }
    
    var currentGame: Game!
    
    func newRound() {
        let newWord = listOfWords.removeFirst()
        currentGame = Game(word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
        updateUI()
    }
    
    func updateUI() {
        scoreLabel.text = "Wins: \(totalWins), Losses: \(totalLosses)"
        treeImageView.image = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)")
    }
}

// Game.swift file code:

import Foundation

struct Game {
    var word: String
    var incorrectMovesRemaining: Int
    var guessedLetters: [Character]
    
    mutating func playerGuessed(letter: Character) {
        guessedLetters.append(letter)
        if !word.contains(letter) {
            incorrectMovesRemaining -= 1
        }
    }
}

I'm a newbie. This is my first program. I appreciate if you code the solution.

CodePudding user response:

You can get the title of the UIButton using titleLabel property. Check the below code.

sender.titleLabel?.text

As the above code returns optional, you can use optional chain to safely get the string

if let titleLabel = sender.titleLabel {
    let title = titleLabel.text
}

OR

You can also use the currentTitle property as below.

sender.currentTitle

CodePudding user response:

You can use: sender.titleLabel.text

  • Related