UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Button title changing trouble

Forums > Swift

@beco0  

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() {
        super.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)
        view.addSubview(mainButton)

        NSLayoutConstraint.activate([
        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)
    }

3      

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

3      

@beco0  

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

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.