比如说我们现在需要控制字数在50字以内我们可以在textview的代理方法中写上这些:
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
if (textView.text.length >= 50 && text.length > range.length) {
//在这里提示用户字数不得超过50字
return NO;
}
return YES;
}
但如果只写这个代理方法,当我们使用中文输入并且具有联想功能的时候程序可能出现如下错误:*** Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'
所以我们需要在textview的另一个代理方法中写上:
-(void)textViewDidChange:(UITextView *)textView
{
//该判断用于联想输入
NSInteger res = 50 - [textView.text length];
if (textView.markedTextRange == nil && 50 > 0 && textView.text.length > 50) {
textView.text = [textView.text substringToIndex:50];
res = 0;
astrictLabel.text =[NSString stringWithFormat:@"还可以输入%d字", res];
}
else {
if (res > 0) {
astrictLabel.text = [NSString stringWithFormat:@"还可以输入%d字", res];
}
else {
astrictLabel.text = [NSString stringWithFormat:@"还可以输入%d字", 0];
}
}
}