iOS开发记录

UITextField只允许输入数字和小数点

2017-07-15  本文已影响29人  陆闪闪

只允许输入数之和小数点,且只能输入一个小数点
<pre>

define NUMBERS @"0123456789."

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSCharacterSet *cs;
NSString * textStr = nil;
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
NSString *filtered = [[text componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest = [text isEqualToString:filtered];
if(!basicTest )
{
return NO;
}
NSString * toBeString = [textView.text stringByReplacingCharactersInRange:range withString:text];
NSLog(@"%@,%@",toBeString,text);

if ([toBeString rangeOfString:@"."].location != NSNotFound&&[[toBeString componentsSeparatedByString:@"."] objectAtIndex:1].length>2 )
{
    //控制输入文本的长度
    return  NO;
}
else if ([toBeString rangeOfString:@"."].location == NSNotFound&&toBeString.length>6){
    //控制输入文本的长度
    return  NO;

}
else if ([textView.text rangeOfString:@"."].location != NSNotFound&& [text isEqual:@"."]){
    //控制输入文本的长度
    return  NO;
    
}
else if (range.location == 0 && [text isEqual:@"."]){

    return NO;
}

else{
    if ([text isEqualToString:@""]&&textView.text.length!= 0) {
        textStr  = [textView.text substringToIndex:textView.text.length-1];
    }
    else{
        textStr = [textView.text stringByAppendingString:text];
        
    }

}

return YES;

}

</pre>

上一篇下一篇

猜你喜欢

热点阅读