【问题标题】:Changing a string's text when a button is pressed in SwiftUI在 SwiftUI 中按下按钮时更改字符串的文本
【发布时间】:2021-01-08 02:22:43
【问题描述】:

我试图弄清楚如何在 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")
        }
    }
    
    
}

到目前为止,我尝试使用 'title.text = (string)' 更改字符串,但这不起作用。有什么想法吗?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    您可以在 ContentView 上将其声明为 @State var buttonTitle: String = "Button Not Clicked",而不是在 body 属性中声明字符串。然后你只需要把buttonTitle = "Button Clicked" 放在你的action 闭包中。

    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")
                }
            }
            
    
        }
        
        
    }
    

    UIKit 的方法是尝试访问标签并更改其字符串,但在 SwiftUI 中,您的 body 属性将在每次 View 更新时有效地重新计算。

    显示多个字符串存储在字典中的附加示例:

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

    【讨论】:

    • 如果我想在 VStack 中拥有多个可编辑的文本元素,我是否将每个元素都声明为 @State 变量?
    • @Piie。如果您有新问题,请创建另一个帖子。如果您的原始问题得到解答,请参阅What should I do when someone answers my question?
    • 您可能希望为每个字符串使用单独的@State 变量,但您可以使用字符串字典。我可以更新示例以显示带有字典的不同示例。您可以采用其他一些方法,例如使用 ObservableObject 创建视图模型。不过,这有点超出了这个问题的范围。
    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2017-12-28
    • 2020-04-07
    相关资源
    最近更新 更多