首页 > 解决方案 > SwiftUI macOS currencyFormatter 不更新绑定变量

问题描述

我有一个带有一个文本字段的 ActionSheet。由于此 Textfield 具有 formatter() 属性,因此它不会每小时更新一次绑定变量。如果我按下“确定”按钮,每小时的值仍然是 0。如果有另一个文本字段并且我单击它,然后按下“确定”按钮,每小时的值是正确的。但我在这张表中只有一个文本字段。

有没有办法保持绑定变量的值更新?

struct AddClientSheet: View {
    @EnvironmentObject var store: Store
    @Environment(\.presentationMode) var presentationMode
    @State private var hourly = 0.0

    var body: some View {
        Form {
            Section(header: Text(“Kunde hinzufügen”).font(.title)) {
                TextField(“Stundenrate”, value: $hourly, formatter: currencyFormatter())
            }
            Divider()
            HStack {
                Spacer()
                Button(action: cancel) {
                    Text("Abbrechen")
                }
                Button(action: addClient) {
                    Text("Hinzufügen")
                }
            }
        }
    }

    func currencyFormatter() -> NumberFormatter {
        let f = NumberFormatter()
        f.numberStyle = .currency
        return f
    }

    func addClient() {
        if hourly > 0{
            //store the data
            self.presentationMode.wrappedValue.dismiss()
        }
    }

    func cancel() {
        self.presentationMode.wrappedValue.dismiss()
    }
}

标签: macosswiftui

解决方案


以下应该可以工作(使用 Xcode 11.2 / macOS 10.15.3 测试)

func addClient() {
    NSApp.keyWindow?.makeFirstResponder(nil) // finish text edit
    if hourly > 0 {
        //store the data
        print(">> hourly = \(hourly)")
        self.presentationMode.wrappedValue.dismiss()
    }
}

推荐阅读