【问题标题】:SwiftUI macOS currencyFormatter does not update binding variableSwiftUI macOS currencyFormatter 不更新绑定变量
【发布时间】:2020-02-26 11:49:22
【问题描述】:

我有一个包含一个文本字段的 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()
    }
}

【问题讨论】:

  • 但我正在开发一个 macOS 应用程序

标签: macos swiftui


【解决方案1】:

以下应该可以工作(使用 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()
    }
}

【讨论】:

    猜你喜欢
    • 2012-03-04
    • 2021-12-06
    • 2021-08-06
    • 2020-05-14
    • 2020-02-24
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多