AntonyCatcher
AntonyCatcher

Reputation: 129

How to change TitleLabel for UIButton?

I have a UITableView with simple content:

The user can edit (delete) the cells when tapping the Edit button the standard way.

I need to change TextLabel from "Edit" to "Done" when the user clicked on "Edit" button.

@IBAction func editButtonPressed(_ sender: UIButton) {
    
    tableView.isEditing = !tableView.isEditing
    
    if tableView.isEditing {
        editButton.titleLabel?.text = "Done"
    } else {
        editButton.titleLabel?.text = "Edit"
    }
}

TitleLabel doesn't change. I need change titleLabel to "Done" when I the user pressed "Edit"

Upvotes: 1

Views: 59

Answers (1)

Andy Jazz
Andy Jazz

Reputation: 58063

Instance method setTitle(_:for:) does the trick.

if tableView.isEditing {
    editButton.setTitle("Done", for: .normal)
} else {
    editButton.setTitle("Edit", for: .normal)
}

Alternatively, you can use ternary expression with ? :

tableView.isEditing.toggle()

tableView.isEditing ? editButton.setTitle("Done", for: []) 
                    : editButton.setTitle("Edit", for: [])

...or its shorter version like @Fogmeister proposed.

editButton.setTitle(tableView.isEditing ? "Done" : "Edit", for: [])

Upvotes: 1

Related Questions