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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.