我想在 SwiftUI 中向 TextField 添加 $ 符号

问题描述

嗨,我想在用户键入时向 TextField 添加 $ 符号。

enter image description here

这是我当前的代码

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

解决方法

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

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()))
        }
    }
}