最近做的app因?yàn)樯婕暗竭m配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:@"字符個(gè)數(shù)不能大于30" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
alert.tag = 100;
[alert show];
textView1.text = [textView.text substringToIndex:30];
number = 30;
}
}
這段代碼在高版本機(jī)器上測試沒問題景图,但是一旦在iOS7上運(yùn)行時(shí)就會(huì)報(bào)錯(cuò):
Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'
github上查閱資料找到了一種解決辦法,通用iOS7以上所有系統(tǒng)版本:
- (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:@"字符個(gè)數(shù)不能大于30" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
alert.tag = 100;
[alert show];
textView1.text = [textView.text substringToIndex:30];
number = 30;
}
}