如何限制UITextField中的小数点数?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何限制UITextField中的小数点数?相关的知识,希望对你有一定的参考价值。
我有一个UITextField,当点击时会在左下角显示一个带小数点的数字键盘。我试图限制该字段,以便用户只能放置1个小数点
例如 2.5好的 2..5不行
像这样实现shouldChangeCharactersInRange方法:
// Only allow one decimal point
// Example assumes ARC - Implement proper memory management if not using.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2 )
return NO;
return YES;
}
这会创建一个由小数点分割的字符串数组,因此如果有多个小数点,则数组中至少有3个元素。
在您设置UITextField委托的任何对象中,添加一个回答"[- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string]
"的方法。
然后你可以使用NSNumberFormatter
对象,也可以对已经存在的小数位标记进行强制检查(如果已存在小数点,则返回NO
)。
简短告诉,数字格式如下[NSString stringWithFormat:@"%9.5f", x];
其中5是“,”之后的小数。
我做了解决方案,让你控制小数位数,所以用户只能输入一个小数点分隔符,你也可以控制小数位数。
只需正确设置decimalPlacesLimit值即可。
看方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(@"text on the way: %@", string);
NSUInteger decimalPlacesLimit = 2;
NSRange rangeDot = [textField.text rangeOfString:@"." options:NSCaseInsensitiveSearch];
NSRange rangeComma = [textField.text rangeOfString:@"," options:NSCaseInsensitiveSearch];
if (rangeDot.length > 0 || rangeComma.length > 0){
if([string isEqualToString:@"."]) {
NSLog(@"textField already contains a separator");
return NO;
} else {
NSArray *explodedString = [textField.text componentsSeparatedByString:@"."];
NSString *decimalPart = explodedString[1];
if (decimalPart.length >= decimalPlacesLimit && ![string isEqualToString:@""]) {
NSLog(@"textField already contains %d decimal places", decimalPlacesLimit);
return NO;
}
}
}
return YES;
}
斯威夫特4
在UITextField中避免多个小数点(。或,)的有效而简单的方法:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(string == "," || string == "." ){
if ((textField.text?.contains(","))! || (textField.text?.contains("."))!){
return false
}
}
return true
}
斯威夫特4
最大整数数是4,即9999,最大十进制数限制是2.因此,最大数可以是9999.99
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// 100 is the tag value of our textfield
/*or you may use "if textfield == myTextField{" if you have an IBOutlet to that textfield */
if textField.tag == 100 {
//max length limit of text is 8
if textField.text!.count > 8 && string != "" {
return false
}
let maxLength = 8
let currentString: NSString = textField.text! as NSString
//使用以下代码如果您要为该文本字段输入价格并希望在用户开始在该文本字段中输入时自动插入$,或者您可以在开头而不是$处放置其他字符。否则请注释以下3行if条件代码
if currentString.length == 0 {
priceTextField.text = "$"
}
//插入新输入的字符后的新字符串
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
if newString.length > maxLength{
return false
}
if (textField.text!.range(of: ".") != nil) {
let numStr = newString.components(separatedBy: ".")
if numStr.count>1{
let decStr = numStr[1]
if decStr.length > 2{
return false
}
}
}
var priceStr: String = newString as String
if (textField.text!.range(of: "$") != nil) {
priceStr = priceStr.replacingOccurrences(of: "$", with: "")
}
let price: Double = Double(priceStr) ?? 0
if price > 9999.99{
return false
}
switch string {
case "0","1","2","3","4","5","6","7","8","9":
return true
case ".":
let array = Array(textField.text!)
var decimalCount = 0
for character in array {
if character == "." {
decimalCount = decimalCount + 1
}
}
if decimalCount == 1 {
return false
} else {
return true
}
default:
let array = Array(string)
if array.count == 0 {
return true
}
return false
}
}
return true
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([string isEqualToString:@"."]) {
BOOL containsDecimal = [textField.text containsString:@"."];
return !containsDecimal;
}
return YES;
}
如果文本字段文本已包含'。'然后返回否则返回YES。
下面是一个带正则表达式的示例,示例仅限于一个小数点和2个小数。您可以调整它以满足您的需求。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = @"^[0-9]*((\.|,)[0-9]{0,2})?$";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])];
return numberOfMatches != 0;
}
对于Swift 2.3来防止用户在两个地方后输入十进制数 -
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
let decimalPlacesLimit = 2
let rangeDot = txtPrice.text!.rangeOfString(".", options: .CaseInsensitiveSearch)
if rangeDot?.count > 0
{
if (string == ".")
{
print("textField already contains a separator")
return false
}
else {
var explodedString = txtPrice.text!.componentsSeparatedByString(".")
let decimalPart = explodedString[1]
if decimalPart.characters.count >= decimalPlacesLimit && !(string == "")
{
print("textField already contains (decimalPlacesLimit) decimal places")
return false
}
}
}
}
在接受的答案的基础上,以下方法验证了处理货币格式时有用的三种情况:
- 数量极大
- 小数点后超过2个字符
- 超过1小数点
确保正确设置了文本字段的委托,您的类符合UITextField
协议,并添加以下委托方法。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Check for deletion of the $ sign
if (range.location == 0 && [textField.text hasPrefix:@"$"])
return NO;
NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *以上是关于如何限制UITextField中的小数点数?的主要内容,如果未能解决你的问题,请参考以下文章