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 Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

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.