Swift NumberFormatter 如果值为 0 return 空字符串
Swift NumberFormatter if value is 0 return empty string
我有以下代码:
struct Food {
var name: String
var energy: Float = 0
var water: Float = 0
}
struct FoodItemView: View {
@State var newFoodItem = Food(name: "")
private var numberFormatter = NumberFormatter()
var body: some View {
Form {
Section(header: Text("Basics").fontWeight(.bold)) {
TextField("Name", text: $newFoodItem.name)
TextField("Energy (C)", value: $newFoodItem.energy, formatter: numberFormatter)
.keyboardType(.numberPad)
TextField("Water (g)", value: $newFoodItem.water, formatter: numberFormatter)
}
}
}
如果绑定值为 0,我如何才能使我的 TextFields 中显示的值为空字符串,而不是显式显示 0?
设置 .zeroSymbol
属性 共 NumberFormatter
。
struct FoodItemView: View {
@State var newFoodItem = Food(name: "")
private var numberFormatter = NumberFormatter()
init() {
numberFormatter.zeroSymbol = "" //<< Here
}
// Other Code
我有以下代码:
struct Food {
var name: String
var energy: Float = 0
var water: Float = 0
}
struct FoodItemView: View {
@State var newFoodItem = Food(name: "")
private var numberFormatter = NumberFormatter()
var body: some View {
Form {
Section(header: Text("Basics").fontWeight(.bold)) {
TextField("Name", text: $newFoodItem.name)
TextField("Energy (C)", value: $newFoodItem.energy, formatter: numberFormatter)
.keyboardType(.numberPad)
TextField("Water (g)", value: $newFoodItem.water, formatter: numberFormatter)
}
}
}
如果绑定值为 0,我如何才能使我的 TextFields 中显示的值为空字符串,而不是显式显示 0?
设置 .zeroSymbol
属性 共 NumberFormatter
。
struct FoodItemView: View {
@State var newFoodItem = Food(name: "")
private var numberFormatter = NumberFormatter()
init() {
numberFormatter.zeroSymbol = "" //<< Here
}
// Other Code