简体   繁体   中英

Changing a string's text when a button is pressed in 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?

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"] = #"╰( ͡° ͜ʖ ͡° )つ──☆*:・゚"#
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM