NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SOLVED: Button title changing trouble

Forums > Swift


Hi, I wanted to make an app that have one big button that change title after its tapped. Also, I'm making it in code, not in storyboards. But when I tap button, code crashes. Do you know what I'm doing wrong?

Here's my code:

var mainButton: UIButton!

    override func viewDidLoad() {

        let mainButton = UIButton(type: .system)
        mainButton.setTitle("Hello, tap here!", for: .normal)
        mainButton.setTitleColor(.white, for: .normal)
        mainButton.titleLabel?.font = UIFont.systemFont(ofSize: 40)
        mainButton.translatesAutoresizingMaskIntoConstraints = false
        mainButton.addTarget(self, action: #selector(mainButtonTapped), for: .touchUpInside)

        mainButton.centerXAnchor.constraint(equalTo: view.layoutMarginsGuide.centerXAnchor),
        mainButton.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.centerYAnchor, constant: -20),
        mainButton.widthAnchor.constraint(equalTo: view.layoutMarginsGuide.widthAnchor),
        mainButton.heightAnchor.constraint(equalTo: view.layoutMarginsGuide.heightAnchor, constant: -100)

    @objc func mainButtonTapped() {
        mainButton.setTitle("Tapped", for: .normal)


Hi, you are not assinging the button to the top level variable mainButton but instead creating local constant and adding that to the view.

You need to remove the let from the first line of your code



Thank you so much, now it looks so simple :D


Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.