如何在 iOS 中构建计算器风格的数字输入字段?
我已经知道如何启用数字键盘并验证字段输入以确保它是数字。我想知道的是如何设置一个输入视图,让用户从右到左输入数值,就像计算器或 ATM 机一样。
换句话说,我希望用户能够输入:
2 0 0 4 9
并将其显示为 $200.49。
然后,一旦输入,我还需要以 NSNumber 或 NSDecimalNumber 的形式在输入视图中或从该输入视图中获取值,并具有正确的小数位置。
例如,我有一个相当于 17.50 的 NSDecimalNumber。我需要能够将此数字传递到键盘视图中进行编辑,然后将编辑后的值作为数字对象返回。
假设用户编辑了该值;他们看到的值是
1 7 5 0
然后他们按退格键。显示的数字将是
1 7 5
我需要将该数字恢复为 1.75,而不是 175 或 17.5。
有什么建议吗?
I already know how to enable the numeric keyboards and validate the field input to ensure it's numeric. What I want to know is how to set up an input view that'll let my user enter a number value from right to left, like a calculator or ATM machine.
In other words, I want the user to be able to type:
2 0 0 4 9
and have that be displayed as $200.49.
Then, once that's been input, I also need to get values in or out of this input view as an NSNumber or NSDecimalNumber, with correct decimal placement.
For example, I have an NSDecimalNumber equivalent to 17.50. I need to be able to pass this number into the keypad view for editing, then get back the edited value as a number object.
Say the user edits that value; the value they see would be
1 7 5 0
Then they hit the backspace key. The number displayed would then be
1 7 5
I need to get that number back as 1.75, not 175 or 17.5.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要格式化字符串,您可以使用 NSNumberFormatter。像这样的东西:
To format the string you can use NSNumberFormatter. Something like this:
我已经实现了内置此功能的SATextField。它的工作方式与 UITextField 类似,并且具有相同的外观。只需将fixedDecimalPoint
属性设置为YES
。编辑: 我创建了一个包含此功能的新项目:STAControls (具体来说,使用
STAATMTextField
-- 它甚至支持.
输入!) 。不同之处在于,该项目已作为UITextField
的合法子类实现,而SATextField
只是容纳UITextField
实例的容器类。I have implemented SATextField that has this functionality built-in. It works just like a UITextField and has the same appearance. Merely set thefixedDecimalPoint
property toYES
.EDIT: I have created a new project that contains this functionality: STAControls (specifically, use
STAATMTextField
-- it even supports.
entry!). The difference is that this project has been implemented as a legitimate subclass ofUITextField
whereasSATextField
was merely a container class housing aUITextField
instance.