iOS UITextField最大字符数和字节数的限制详解

2020-01-18 18:16:56于丽

这里不能只在进行限制,在textFieldDidChange中需要对中文联想做处理才行

三. 放弃键盘

1. 能拿到uitextfield的时候用


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
 return [textField resignFirstResponder];
}

2. 点击view消失的时候用


[self.view endEditing:YES];

3. 难以获取的时候用


[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

或者


[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

4.Tableview点击空白处或者滚动时消失


{
 UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
 [self.view addGestureRecognizer:singleTap];
}

#pragma mark- 键盘消失
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer{
 [self.view endEditing:YES];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
 [self.view endEditing:YES];
}

四. 正则表达式限制

请参考 正则表达式语法表 ,这里我提供了两种表达式给大家参考,一个Int,一个无unsignedInt


-(BOOL) isTextFieldMatchWithRegularExpression:(NSString *)exporession{
 
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",exporession];
 return [predicate evaluateWithObject:self];
}
-(BOOL) isTextFieldIntValue{
 return [self isTextFieldMatchWithRegularExpression:@"[-]{0,1}[0-9]*"];
}
-(BOOL) isTextFieldUnsignedIntValue{
 return [self isTextFieldMatchWithRegularExpression:@"[0-9]+"];
}

五. UITextfield的键盘事件多次回调问题

1.键盘高度遮挡问题

一般出现遮挡的时候我们用以下代码,看看当前textfield是否在键盘下面,在的话算出键盘的顶端和textfield的底部的距离,然后做偏移动画


- (void)keyboardWillShow:(NSNotification *)notification {
 
 NSDictionary *userInfo = [notification userInfo];
 
 NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
 CGRect keyboardRect = [aValue CGRectValue];
 keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
 
 CGFloat keyboardTop = keyboardRect.origin.y;
 
 CGFloat offset = self.normalTextField.frame.size.height + self.normalTextField.frame.origin.y - keyboardTop;
 
 NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
 NSTimeInterval animationDuration;
 [animationDurationValue getValue:&animationDuration];
 
 if(offset > 0){
 // Animate the resize of the text view's frame in sync with the keyboard's appearance.
 [UIView beginAnimations:nil context:NULL];
 [UIView setAnimationDuration:animationDuration];

 CGRect rect = CGRectMake(0.0f, -offset,self.view.frame.size.width,self.view.frame.size.height);
 self.view.frame = rect;
 [UIView commitAnimations];
 }
}