Hi I want to add $ sign to a TextField when a user is typing.
![enter image description here](https://i.stack.imgur.com/xc738.png)
这是我当前的代码。
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()))
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)