Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a string's text when a button is pressed in SwiftUI

Tags:

swift

swiftui

I'm trying to figure out how to change the text of a string when a button is pressed in SwiftUI.

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
           let title = Text("Button Not Clicked")
                .font(.title)
                .fontWeight(.heavy)
                .foregroundColor(.red)
                .padding()
                .frame(height: 0.0)
        }
        
        Button(action: {
            title.text = "Button Clicked!"
        }) {
            Text("Click Here")
        }
    }
    
    
}

So far, I've tried to change the string using 'title.text = (string)' but that doesn't work. Any ideas?

like image 514
Piie. Avatar asked Nov 01 '25 22:11

Piie.


1 Answers

Instead of declaring the string in the body property you can declare it as a @State var buttonTitle: String = "Button Not Clicked" on ContentView. Then you just need to put buttonTitle = "Button Clicked" in your action closure.

import SwiftUI

struct ContentView: View {
    @State var buttonTitle: String = "Button Not Clicked"
    var body: some View {
        VStack {
           Text(buttonTitle)
                .font(.title)
                .fontWeight(.heavy)
                .foregroundColor(.red)
                .padding()
                .frame(height: 0.0)

            Button(action: {
                buttonTitle = "Button Clicked!"
            }) {
                Text("Click Here")
            }
        }
        

    }
    
    
}

The UIKit way would be to try to access the label and change its string, but in SwiftUI your body property will effectively be recalculated every time the View updates.

Additional example showing multiple strings being stored in a dictionary:

struct ContentView: View {
    @State var labels: [String : String] = [
        "header" : "This Is the header!",
        "donger" : "",
        "footer" : "Here's the footer."
        
    ]
    
    var body: some View {
        VStack {
            Text(labels["header"]!)
            Text(labels["donger"]!)
            Text(labels["footer"]!)
            
            Spacer()
            
            Button("Update") {
                updateDonger()
            }
        }
    }
    
    func updateDonger() {
        labels["donger"] = #"╰( ͡° ͜ʖ ͡° )つ──☆*:・゚"#
    }
}
like image 191
Sparklebeard Avatar answered Nov 03 '25 11:11

Sparklebeard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!