swift TextField不将输入文本绑定到变量

ppcbkaq5  于 2023-01-25  发布在  Swift
关注(0)|答案(1)|浏览(97)

在我看来,我使用的是TextField。我有一个状态变量绑定到TextField的输入,但似乎绑定到TextField的变量在用户输入一些文本时根本不改变值。我没有任何错误。有人知道如何使TextField输入绑定到字符串变量吗?

import SwiftUI

struct UploadJobView: View {
    @State private var caption = ""
    @State private var new = "Hello"

    var body: some View {
        VStack{
             TextField("caption", text: $caption)
                   .onChange(of: caption, perform: { _ in
                       new = caption
                   })
             Text(new)
        }
    }
}
umuewwlo

umuewwlo1#

Does anyone know how to make the TextField input bind to a string var?
是的,在Xcode 14中,创建一个新的ios项目,并用下面的示例代码替换生成的ContentView
在ios设备或模拟器或maccatalyst上运行代码。对我来说效果很好。

struct ContentView: View {
    var body: some View {
        UploadJobView()
    }
}

struct UploadJobView: View {
    @State private var caption = ""
    @State private var new = "Hello"
    
    var body: some View {
        VStack {
            TextField("caption", text: $caption)
                .onChange(of: caption) { _ in
                    new = caption
                }
            Text(new)
        }
    }
}

相关问题