[英]SwiftUI TextField + Stepper
我正在尝试实现一个带有数字输入的 TextField 以及 Stepper 来控制数量。 在 TextField 中输入数字后,Stepper 将失去更改数字的能力。 我很确定 Binding 值有一个技巧,但无法弄清楚到底是什么。
struct TestView: View {
@State var quantity: Int = 0
var body: some View {
HStack {
TextField("", value: $quantity, formatter: NumberFormatter())
Stepper("", onIncrement: {
self.quantity += 1
}, onDecrement: {
self.quantity -= 1
})
}
}
}
这是因为在TextField
中使用NumberFormatter
存在漏洞。
您可能需要改用自定义绑定:
struct ContentView: View {
@State var quantity: Int = 0
static let formatter = NumberFormatter()
var binding: Binding<String> {
.init(get: {
"\(self.quantity)"
}, set: {
self.quantity = Int($0) ?? self.quantity
})
}
var body: some View {
HStack {
TextField("", text: binding)
Stepper("", onIncrement: {
self.quantity += 1
}, onDecrement: {
self.quantity -= 1
})
}
}
}
也不要每次都重新创建NumberFormatter
:
TextField("", value: $quantity, formatter: NumberFormatter())
您可以使用仅创建一次的 static 属性:
static let formatter = NumberFormatter()
我对Stepper
和TextField
也有类似的问题,所以我决定制作一个 Swift package 来解决这个问题。
在 TextField 中输入数字后,Stepper 将失去更改数字的能力。
我也遇到了这个问题,实际上发现onIncrement
和onDecrement
操作继续相应地被解雇。 但是,我注意到,通过持续闪烁 cursor 观察到,使用Stepper
不会释放用户对TextField
的关注。
在用户使用Stepper
时从TextField
中移除焦点可以解决此问题。
这在查阅TextField
文档时也很有意义:
如果该值为字符串,则文本字段会在用户键入或以其他方式编辑字段中的文本时不断更新此值。 对于非字符串类型,它会在用户提交编辑时更新值,例如按 Return 键。
(来源: https://developer.apple.com/documentation/swiftui/textfield )
因此,我建议在用户使用Stepper
时模拟用户提交事件。 这避免了不必要的类型转换,并允许您继续利用TextField
formatter
初始化程序。
原代码修改示例:
struct TestView: View {
@State var quantity: Int = 0
// Keep track of which field the user is focused on
@FocusState private var focusedField: String?
var body: some View {
HStack {
TextField("", value: $quantity, formatter: NumberFormatter())
.focused($focusedField, equals: "quantity")
Stepper("", onIncrement: {
// Remove the focus from the (text) field
focusedField = nil
self.quantity += 1
}, onDecrement: {
// Remove the focus from the (text) field
focusedField = nil
self.quantity -= 1
})
}
}
}
有关详细信息,另请参阅focused(_:equals:)
和@FocusState
文档: https://developer.apple.com/documentation/swiftui/view/focused(_:equals:) https://developer.apple。 com/文档/SwiftUI/FocusState
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.