以下两法方法都是实现textfield和textView的代理方法 需要先遵循代理
一:textField限制只能输入数字和小数点 且小数点后只能保留两位 小数点前最多5位
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // 输入框中的值 只能输入到小数点后两位 if (string.length == 0) { return YES; } const char * ch=[string cStringUsingEncoding:NSUTF8StringEncoding]; if(*ch == 0) return YES; if( *ch != 46 && ( *ch<48 || *ch>57) ) return NO; if([textField.text rangeOfString:@"."].length==1) { NSUInteger length=[textField.text rangeOfString:@"."].location; if([[textField.text substringFromIndex:length] length]>2 || *ch ==46) return NO; }else{ NSInteger existedLength = textField.text.length; NSInteger selectedLength = range.length; NSInteger replaceLength = string.length; if (existedLength - selectedLength + replaceLength > 5&&![string isEqualToString: @"."]) { return NO; } } return YES; }
二:textView限制输入字数,这里限制为25字以内
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@""] && range.length > 0) { return YES; }else { if (textView.text.length - range.length + text.length > 25) { return NO; }else { return YES; } } }
时间: 2024-10-13 01:02:10