简体   繁体   English

在 SwiftUI 中按下按钮时更改字符串的文本

[英]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.我试图弄清楚在 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.到目前为止,我尝试使用 'title.text = (string)' 更改字符串,但这不起作用。 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.您可以将其声明为@State var buttonTitle: String = "Button Not Clicked" on ContentView,而不是在 body 属性中声明字符串。 Then you just need to put buttonTitle = "Button Clicked" in your action closure.然后,您只需将buttonTitle = "Button Clicked"放入您的操作闭包中。

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. UIKit 方法是尝试访问 label 并更改其字符串,但在 SwiftUI 中,您的 body 属性将在每次视图更新时有效地重新计算。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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