Fork me on GitHub

UITextField 限制用户输入小数点后位数的方法

UITextField 限制用户输入小数点后位数的方法

位数限制: limited

在UITextField的代理方法中添加类似如下代码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    NSMutableString * futureString = [NSMutableString stringWithString:textField.text];
    [futureString  insertString:string atIndex:range.location];
    
    NSInteger flag=0;
    const NSInteger limited = 1;
    for (int i = futureString.length-1; i>=0; i--) {

        if ([futureString characterAtIndex:i] == '.') {
            
            if (flag > limited) {
                return NO;
            }
            
            break;
        }
        flag++;
    }
    
    return YES;
}

 

posted @ 2017-05-17 17:45  极度恐慌_JG  阅读(513)  评论(0编辑  收藏  举报