在项目中,当我们用到TextField
时,必然需要对其进行一些限制,在此总结如下。
对TextField
进行限制,必然需要实现其delegate
。
// 控制当前输入框能否被编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;
// 当输入框开始时触发(获得焦点触发)
- (void)textFieldDidBeginEditing:(UITextField *)textField;
// 询问输入框是否可以结束编辑(键盘是否可以收回)
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
// 当前输入框结束编辑时触发(键盘收回之后触发)
- (void)textFieldDidEndEditing:(UITextField *)textField;
// 当前输入框结束编辑原因(iOS10.0支持)
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason API_AVAILABLE(ios(10.0));
// 当输入框文字发上变化时触发(只有通过键盘输入时,文字改变,触发)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
// 输入内容发生改变后触发(iOS13支持)
- (void)textFieldDidChangeSelection:(UITextField *)textField API_AVAILABLE(ios(13.0), tvos(13.0));
// 控制输入框清除按钮是否有效
- (BOOL)textFieldShouldClear:(UITextField *)textField;
// 控制键盘是否收回(点击键盘上的return的时候调用)
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
-
限制输入长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//原有的字符串拼接输入的字符串
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//转换过的长度
NSInteger length = [self textLength:newString];
if (length > 12)
{
return NO;
}
return YES;
}
-(NSUInteger)textLength:(NSString *) text{
NSUInteger asciiLength = 0;
for (NSUInteger i = 0; i < text.length; i++) {
unichar uc = [text characterAtIndex: i];
//设置汉字和字母的比例 如果限制4个汉字或12个字母 就是1:3 如果限制是6个汉字或12个字符 就是 1:2 以此类推
asciiLength += isascii(uc) ? 1 : 1;
}
NSUInteger unicodeLength = asciiLength;
return unicodeLength;
}
-
限制字符输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//只允许输入一个小数点
if ([textField.text containsString:@"."] && [string isEqualToString:@"."]) {
return NO;
}
//小数点不能为第一位
if (textField.text.length == 0 && [string isEqualToString:@"."]) {
return NO;
}
//限制小数点后只能输一位数字
NSArray * arrStr = [[textField.text stringByAppendingString:string] componentsSeparatedByString:@"."];
if (arrStr.count>1) {
NSString *str1 = arrStr.lastObject;
if (str1.length>1) {
return NO;
}
}
//限制只能输入 "-0123456789."
NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"-0123456789."];
BOOL res = YES;
int i = 0;
while (i < string.length) {
NSString * string = [string substringWithRange:NSMakeRange(i, 1)];
NSRange range = [string rangeOfCharacterFromSet:tmpSet];
if (range.length == 0) {
res = NO;
break;
}
i++;
}
return res;
}