IOS开发问题解决之限制UITextField输入特定位数小数时,Done按钮失效

问题描述

      要求是限制UITextField只能输入一位小数。我的方法是重写delegate的textField:shouldChangeCharactersInRange:replacementString:函数。自己写的代码如下:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    isHasRadixPoint = YES;
    NSString *existText = textField.text;
    if ([existText rangeOfString:@"."].location == NSNotFound) {
        isHasRadixPoint = NO;
    }
    if (string.length > 0) {
        unichar newChar = [string characterAtIndex:0];
        if ((newChar >= '0' && newChar <= '9') || newChar == '.' ) {
            if (newChar == '.') {
                if (isHasRadixPoint) 
                    return NO;
                else 
                    return YES;                
            }else {
                if (isHasRadixPoint) {
                    NSRange ran = [existText rangeOfString:@"."];
                    int radixPointCount = range.location - ran.location;
                    if (radixPointCount <= RadixPointNum) return YES;
                    else return NO;
                } else 
                    return YES;
            }
            
        }else {
            return NO;
        }
        
    }else {
        return YES;
    }
}

     写完测试,这时问题来了。键盘上的"Done"按钮失效了。上面代码中的RandixPointNum是在文件最上边部分定义的宏,代表小数点位数。

解决方法

     “Done”按钮其实就是字符“\n”,由于上面的代码将其过滤了,导致了其事件失效。修改后代码如下,注意有注释的那行:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    isHasRadixPoint = YES;
    NSString *existText = textField.text;
    if ([existText rangeOfString:@"."].location == NSNotFound) {
        isHasRadixPoint = NO;
    }
    if (string.length > 0) {
        unichar newChar = [string characterAtIndex:0];
        if ((newChar >= '0' && newChar <= '9') || newChar == '.' ) {
            if (newChar == '.') {
                if (isHasRadixPoint) 
                    return NO;
                else 
                    return YES;                
            }else {
                if (isHasRadixPoint) {
                    NSRange ran = [existText rangeOfString:@"."];
                    int radixPointCount = range.location - ran.location;
                    if (radixPointCount <= RadixPointNum) return YES;
                    else return NO;
                } else 
                    return YES;
            }
            
        }else {
            if ( newChar == '\n') return YES;       // 这句非常重要:不然将导致“Done”按钮失效
            return NO;
        }
        
    }else {
        return YES;
    }
}

问题总结

    虽然同样也完成了任务,总觉得这样写不是特别好,不知还有没有好的方法。


你可能感兴趣的:(IOS开发问题解决之限制UITextField输入特定位数小数时,Done按钮失效)