Textfield崩溃中的NSnumber转换
我遇到了旧问题,但找不到解决方案:
我有一个简单的视图:
struct ContentView: View {
@State var myInt: Int = 0
var body: some View {
TextField("Int", value: $myInt, formatter: NumberFormatter())
}
}
在运行时,输入'111111111111111111',或任何20位或更多的数字或更多的东西,以:
“致命错误:无法将nsnumber桥接到int:file”
如果将类型更改为:
@State var myInt: NSNumber = 0
输入的值转换为'1111111111111111110000',并且不会崩溃。
我的问题是,我希望MyInt是INT类型,而不是Nsnumber,同时又不会崩溃。
我尝试了几次尝试将字符串转换为nsnumber的INT,但无效。
尝试1:使用绑定,在设置器中进行验证
var body: some View {
TextField("Int", value: Binding(
get: { myInt },
set: {
var fixedInt: Int
if $0 > 9223372036854775807 { fixedInt = 0 } else { fixedInt = $0 }
myInt = fixedInt }
), formatter: NumberFormatter())
}
}
不幸的是,问题仍然存在。
I went through old questions but couldn't find a solution for this:
I have this simple View:
struct ContentView: View {
@State var myInt: Int = 0
var body: some View {
TextField("Int", value: $myInt, formatter: NumberFormatter())
}
}
In runtime, entering '1111111111111111111', or any 20 digits or more into the TextField crashes with:
"Fatal error: Unable to bridge NSNumber to Int: file"
If I change the type to:
@State var myInt: NSNumber = 0
the entered value is converted to '111111111111111110000' and it's not crashing.
My problem is, I want myInt to be of type Int, not NSNumber, while staying safe from crashing.
I made several attempts to convert String to NSNumber to Int but nothing worked.
Attempt 1: Using a Binding, validating in the setter
var body: some View {
TextField("Int", value: Binding(
get: { myInt },
set: {
var fixedInt: Int
if $0 > 9223372036854775807 { fixedInt = 0 } else { fixedInt = $0 }
myInt = fixedInt }
), formatter: NumberFormatter())
}
}
Unfortunately, the problem persists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
多亏了评论,这使我更好地关注了我的问题,我找到了解决方案。
首先,我终于了解了如何访问NumberFormatter属性。对我来说还不清楚。我可以将它们设置在init()中:
令我惊讶的是,给出值92223372036854775808和922233720372036854775809。它在理论上并不完全令人满意,但实际上,我的应用程序会较低,所以我的应用程序较低,所以我的估值不是完全满意的可以设置:
当然,或更少。
Thanks to the comments and which led me to focussing better on my question, I found a solution.
First, I finally understood how to access NumberFormatter properties. It wasn't clear to me. I can set them in init():
To my surprise, it is still possible to crash with giving the values 9223372036854775808 and 9223372036854775809. It is not entirely satisfactory in theory, but practically, the values my app will be using are lower, so I can set:
or less, of course.