NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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 NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.