MPNumericTextField
是一个扩展了基本 UITextField
的类,使您能够轻松地在文本框中输入格式化的数字。
它可以正确处理十进制数字、整数、百分比和货币值,使用当前区域设置或手动提供的区域设置。
只需将以下主要文件添加到您的项目中
MPNumericTextField.h
MPNumericTextField.m
MPNumericTextFieldDelegate.h
MPNumericTextFieldDelegate.m
MPFormatterUtils.h
MPFormatterUtils.m
这些文件可以在 Classes
文件夹中找到。
您可以使用以下代码创建一个非常简单的数字文本字段
MPNumericTextField *textField = [[MPNumericTextField alloc] init];
这将创建一个将使用当前区域设置和本地文本字段代理实现(请参阅 MPNumericTextFieldDelegate.{h|m}
)处理十进制数字输入的文本字段。
您可以通过 type
属性更改文本字段的默认数字样式。它可以设置为以下值之一
MPNumericTextFieldDecimal
(默认值)MPNumericTextFieldInteger
MPNumericTextFieldCurrency
MPNumericTextFieldPercentage
例如,要将文本字段的数字样式更改为货币,请执行以下操作
numericTextField.type = MPNumericTextFieldCurrency;
您可以通过 numericValue
属性访问文本字段的数字值。例如
MPNumericTextField *textField = [[MPNumericTextField alloc] init];
textField.type = MPNumericTextFieldPercentage;
textField.numericValue = @(2.25);
// ... (make changes to the text field) ...
NSNumber *currentValue = textField.numericValue;
默认情况下,MPNumericTextField
将使用 [NSLocale currentLocale]
区域设置。但是,您也可以轻松地更改此属性
numericTextField.locale = myCustomLocale;
当使用 MPNumericTextField
来显示货币时,一个旧的限制是必须依赖于 NSLocale
提供的货币代码。
从版本 1.3.0 开始,您可以设置自定义货币代码来表示这些值,使用所需的货币
numericTextField.currencyCode = @"JPY";
MPNumericTextField
类通过无缝使用 MPNumericTextFieldDelegate
类作为其自己的代理来处理所有逻辑,该代理在用户输入数字时使文本字段以正确格式绘制数字。
您可以选择为您的对象设置一个新的自定义代理,并且 MPNumericTextField
将将它们作为前向代理来处理,以确保它们与现有的代理正确工作。
与该库的 1.0.0 版本不同,从 1.1.0 版本开始,您可以使用来自 UITextField
的标准 -setDelegate:
和 -delegate
方法来设置自定义代理,而无需担心基本数字字段功能。
您可以更改文本字段中的默认占位符颜色。只需使用 placeholderColor
属性即可。
numericTextField.placeholderColor = [UIColor redColor];
如果此属性设置为 nil
,则将使用默认的系统颜色。
您可以自由修改此项目的源代码,并在 Github 上提交拉取请求,以便将您的贡献合并到原始项目中。
如果您需要进一步的帮助,请通过 Twitter 联系我:@marzapower。
版本 1.4.0
MPTextField
类打开了在处理数字文本字段之外的 placeholderColor
的使用。版本 1.3.0
MPFormatterUtils
中的实用方法中添加了可空性修饰符版本 1.2.1
版本 1.2.0
MPNumericTextFieldInteger
添加了对只包含整数的数字的支持版本 1.1.0
MPNumericTextFieldDelegate
中所有代理方法的支持MPNumericTextField
中添加了 IB_DESIGNABLE 关键字版本 1.0.0