SwiftUI的TextField在值更改时未更新

3

我有一个表单上的文本框,用户可以在其中输入值,但我还想通过按钮更新文本框的内容。

以下是我的代码:

struct test: View {
@State private var amount: Double = 0.0

var body: some View {
    Form {
        VStack {
            HStack {
                Text("Amount EUR")
                Spacer()
                TextField("Type amount", value: $amount, format: .number)
                    .keyboardType(.numberPad)
                    .multilineTextAlignment(.trailing)
            }
            
            Text("Set MAX (999)")
                .frame(maxWidth: .infinity, alignment: .leading)
                .onTapGesture {
                    print("before tap \(amount )")
                    amount = 999
                    print("after tap \(amount)")
                }
            
        }
    }
}

当我刚启动应用程序时,第一次点击文本会将文本字段更新为999,但之后就不再起作用了。 amount的值已正确更新,但文本字段没有反映出变化。
你能解释一下吗?
1个回答

7
答案很简单,TextFields在获得焦点时不会更新。为了解决这个问题,您需要在视图中加入 @FocusState 并在更新变量之前使 TextField 失去焦点。您可以在进入 TextField 之前先轻触您的 Text,然后进行测试,您会发现它可以正常更新。
struct ButtonUpdateTextField: View {
    @State private var amount: Double = 0.0
    @FocusState var isFocused: Bool // <-- add here
    
    var body: some View {
        Form {
            VStack {
                HStack {
                    Text("Amount EUR")
                    Spacer()
                    TextField("Type amount", value: $amount, format: .number)
                        .keyboardType(.numberPad)
                        .multilineTextAlignment(.trailing)
                        .focused($isFocused) // <-- add here
                }
                
                Text("Set MAX (999)")
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .onTapGesture {
                        print("before tap \(amount )")
                        isFocused = false // <-- add here
                        amount = 999
                        print("after tap \(amount)")
                    }
                
            }
        }
    }
}

1
我们是否知道为什么当焦点在文本框中时绑定更改时,TextField不会更新?令人惊讶的难以找到这些信息。无论如何,这个解决方法对我来说并没有完全奏效 - 我必须使用asyncAfter()延迟绑定变量的更新,直到焦点更改有足够的时间生效。还是非常有用的答案,谢谢! - biomiker
这对我来说也不起作用。从asyncAfter开始,我能够将其简化为在简单的DispatchQueue.main.async中更新绑定值。不需要使用@FocusState,只需DispatchQueue.main.async { amount = newValue } - bauerMusic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接