UITextView输入文本时限定输入字符数量

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // 键盘的Enter键
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        
        return NO;
    }
    
    int wordCount = [textView.text length] + text.length;
    if(wordCount > _totalWord){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"字数限制"
                                                        message:[NSString stringWithFormat:@"不能超过%i字的上限哦!", _totalWord]
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil
                              ];
        [alert show];
        return NO;
    }else {
        self.wordnum.text = [NSString stringWithFormat:@"%d字", _totalWord - wordCount];
    }
    
	return YES;
}

 

你可能感兴趣的:(UITextView)