如何在文本字段中显示和编辑小数值?

问题描述 投票:0回答:2

我正在开发一个 SwiftUI 项目,我需要允许用户在 TextField 中输入十进制值。然而,SwiftUI 的 TextField 的默认行为似乎只支持整数值。我想知道如何修改 TextField 以接受和显示十进制值。

我尝试在文本字段上使用格式化程序:numberFormatter() 属性和keyboardType(.decimalPad) 修饰符,但它似乎并不影响行为。 TextField 仍然只允许我输入整数。

这是代码示例。项目列表如下所示。我想显示和编辑对象的价格属性。

@State private var items: [Item] = [
    Item(name: "Item 1", quantity: 10, price: 10.5),
    Item(name: "Item 2", quantity: 5, price: 12.5),
    Item(name: "Item 3", quantity: 3, price: 16000.3)
]
...

文本字段如下所示,

...

HStack {
    TextField("Item Description", text: $items[index].name)
        .multilineTextAlignment(.center)
    TextField("Quantity", value: $items[index].quantity, formatter: NumberFormatter())
        .multilineTextAlignment(.center)
    TextField("Price", value: $items[index].price, formatter: NumberFormatter())
        .keyboardType(.decimalPad)
        .multilineTextAlignment(.center)
}
swiftui textfield nsdecimalnumber
2个回答
1
投票

您不应该像这样内联初始化对象:

formatter: NumberFormatter()
这是内存泄漏,要么使用静态对象,要么使用新的便利性
format: .currency
。另外
ForEach
不是 for 循环,你不应该有
$items[index].name
因为它会崩溃。而是使用
ForEach($items) { $item in
,然后使用
text: $item.name
Item
应该是
Identifiable


0
投票
HStack {
    TextField("Item Description", "Item Description", text: $items[index].name)
        .multilineTextAlignment(.center)

    TextField("Quantity", value: $items[index].quantity ,format: .number)
        .multilineTextAlignment(.center)

    TextField("Price", value: $$items[index].price ,format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
          .keyboardType(.decimalPad)
          .multilineTextAlignment(.center)
                
}
© www.soinside.com 2019 - 2024. All rights reserved.