英文:
How to bridge from Binding<Float> to Binding<String> using an Extension in SwiftUI?
问题
以下是您要翻译的内容:
Context
我有一个将Binding
限制为Float
的Extension
,将其转换为String
以在SwiftUI
的TextField
中使用。然而,在无法确定导致问题的原因时,我遇到了两种奇怪的行为:
-
当输入超过4位数时,例如12345,
TextField
会清空。 -
当输入小数分隔符(例如美国的".")时,
TextField
会清空。
Code
public extension Binding where Value == Float {
var adapter: Binding<String> {
Binding<String>(
get: {
guard self.wrappedValue != -1 else { return "" }
let formatter = NumberFormatter()
formatter.locale = Locale.current
formatter.numberStyle = .decimal
return formatter.string(from: NSNumber(value: self.wrappedValue)) ?? ""
},
set: {
let formatter = NumberFormatter()
formatter.locale = Locale.current
formatter.numberStyle = .decimal
self.wrappedValue = formatter.number(from: $0)?.floatValue ?? -1
}
)
}
}
如果您需要进一步的帮助,请随时提问。
英文:
Context
I have an Extension
of Binding
limited to Float
which converts it into a String
for usage with the SwiftUI
TextField
. However, I encountered two odd behaviours while not being able to identify the causing issues:
-
When entering more than 4 digits, e.g. 12345, the
TextField
empties -
When entering a decimal separator (e.g. "." in the US), the
TextField
empties
Code
public extension Binding where Value == Float {
var adapter: Binding<String> {
Binding<String>(
get: {
guard self.wrappedValue != -1 else { return "" }
let formatter = NumberFormatter()
formatter.locale = Locale.current
formatter.numberStyle = .decimal
return formatter.string(from: NSNumber(value: self.wrappedValue)) ?? ""
},
set: {
let formatter = NumberFormatter()
formatter.locale = Locale.current
formatter.numberStyle = .decimal
self.wrappedValue = formatter.number(from: $0)?.floatValue ?? -1
}
)
}
}
Question
- What causes these errors and how can I achieve my goal of bridging from
Binding<Float>
toBinding<String>
?
答案1
得分: 1
不要重新发明轮子,而是使用新的格式化样式
@State private var value: Float = 0
var body: some View {
//...
TextField("值", value: $value, format: .number)
//...
}
英文:
Don't reinvent the wheel, instead use the new formatting style
@State private var value: Float = 0
var body: some View {
//...
TextField("Value", value: $value, format: .number)
//...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论