最近做的app因为涉及到适配iOS7测试阶段遇到了很多的bug,不得不说iOS7适配非常的坑爹,其中UITextView限制输入字符在iOS7中非常特殊,高版本限制字符代码如下:
- (void)textViewDidChange:(UITextView *)textView1 {
NSInteger number = [textView1.text length];
NSInteger maxLength = 30;
if (textView1.text.length > maxLength) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"字符个数不能大于30" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
alert.tag = 100;
[alert show];
textView1.text = [textView.text substringToIndex:30];
number = 30;
}
}
这段代码在高版本机器上测试没问题,但是一旦在iOS7上运行时就会报错:
Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'
github上查阅资料找到了一种解决办法,通用iOS7以上所有系统版本:
- (void)textViewDidChange:(UITextView *)textView1 {
NSInteger number = [textView1.text length];
NSInteger maxLength = 30;
if (textView1.markedTextRange == nil && textView1.text.length > maxLength) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"字符个数不能大于30" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
alert.tag = 100;
[alert show];
textView1.text = [textView.text substringToIndex:30];
number = 30;
}
}
网友评论