textField和textView限制輸入條件,textfieldtextview
以下兩法方法都是實現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; } }}