- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (string.length<=0) {
return YES;
}
//1.拼音输入且删除的操作时,都返回YES
if ([textField positionFromPosition:[textField markedTextRange].start offset:0] && range.length >= 1 && string.length == 0) {
return YES;
}
//2.拼音输入且在增加文字时,返回YES
if ([textField positionFromPosition:[textField markedTextRange].start offset:0] && range.length == 0) {
return YES;
}
//修改后的文本
NSString *comcatStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSInteger canInputLen = 0;
canInputLen = 5 - comcatStr.length;
if (canInputLen >= 0)
{
return YES;
}
else
{
NSInteger len = string.length + canInputLen;
//防止当text.length + caninputlen < 0时,使得rg.length为一个非法最大正数出错
NSRange rg = {0,MAX(len,0)};
if (rg.length > 0)
{
NSString *s = [string substringWithRange:rg];
[textField setText:[textField.text stringByReplacingCharactersInRange:range withString:s]];
//既然是超出部分截取了,哪一定是最大限制了。
}
return NO;
}
return YES;
}
网友评论