【问题标题】:I want to add $ sign to TextField in SwiftUI我想在 SwiftUI 中向 TextField 添加 $ 符号
【发布时间】:2021-06-08 13:42:05
【问题描述】:

您好,我想在用户输入时向 TextField 添加 $ 符号。

这是我当前的代码。

ZStack(alignment: .leading) {
  if price.isEmpty {
    Text("Enter total budget")
  }
  HStack {
    TextField("", text: $price)
      .keyboardType(.decimalPad)
  }
}

【问题讨论】:

  • TextField 中使用某种货币格式化程序可能是合理的,它不会在输入过程中即时进行格式化,但它肯定会在编辑完成时格式化输入值。跨度>
  • 你的应用只支持美元吗?

标签: swiftui textfield


【解决方案1】:

货币格式化程序是要走的路,但如果您只想在键入时在 TextField 中显示一个 $,您可以使用如下内容: (您当然可以将此方法与 Formatter 结合使用)

struct ContentView: View {
    @State var price = ""
    
    var body: some View {
        VStack {
            ZStack(alignment: .leading) {
                if price.isEmpty {
                    Text("Enter total budget")
                }
                HStack {
                    TextField("", text: Binding(
                        get: { price },
                        set: { newVal in
                        if price.starts(with: "$") {
                            price = newVal
                        } else {
                            price = "$" + newVal
                        }
                    })).keyboardType(.decimalPad)
                }
            }.padding(20)
            Text("number entered: " + String(price.dropFirst()))
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 2020-06-11
    • 2020-05-12
    • 1970-01-01
    • 2019-11-22
    • 2021-07-25
    • 1970-01-01
    • 2021-08-06
    • 2020-10-19
    相关资源
    最近更新 更多