[转]如何控制textview中的字数(包括联想字符的处理)
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if([[textView text] length]>MaxNumberOfDescriptionChars){
return NO;
}
//判断是否为删除字符,如果为删除则让执行
char c=[text UTF8String][0];
if (c=='\000') {
numberOfCharsLabel.text=[NSString stringWithFormat:@"%d",MaxNumberOfDescriptionChars-[[textView text] length]+1];
return YES;
}
if([[textView text] length]==MaxNumberOfDescriptionChars) {
if(![text isEqualToString:@"\b"]) return NO;
}
numberOfCharsLabel.text=[NSString stringWithFormat:@"%d",MaxNumberOfDescriptionChars-[[textView text] length]-[text length]];
return YES;
}
//常常由于联想输入的缘故,会有很多字符一起输入
-(void)textViewDidChange:(UITextView *)textView{
//该判断用于联想输入
if (textView.text.length > MaxNumberOfDescriptionChars)
{
textView.text = [textView.text substringToIndex:MaxNumberOfDescriptionChars];
}
}