iOS TextField限制字数功能,无需截取,体验较好,类似
2018-04-29 本文已影响0人
LYY_DADADA
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSInteger maxLength = 7;
NSMutableString *stringTarget = [NSMutableString string];
NSString *alreadyExistString = [textField.text substringToIndex:range.location];
[stringTarget appendString:alreadyExistString];
if (range.length != 0) {
[stringTarget appendString:string];
}
else {
// 此处必须包含等于
if (stringTarget.length >= maxLength && string.length != 0) {
return NO;
}
else {
[stringTarget appendString:[textField.text substringFromIndex:range.location]];
}
}
// 会出现一种情况,就是当你输入完一些字以后,系统自动给出智能提示的字供 选择,此时不符合以上逻辑
// 这里做一些防错处理
if (range.location + string.length > maxLength) {
return NO;
}
if (stringTarget.length > maxLength && string.length != 0) {
return NO;
}
return YES;
}