iOS UITextView limit the number of words

Monitor content changes

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:nil];
复制代码

Processing restrictions

-(void)textViewDidChangeNotification:(NSNotification *)notification{
    UITextView * textView = (UITextView *)notification.object;
    
    // 需要限制的长度
    NSUInteger maxLength = _maxTextLength ?: NSIntegerMax;
    
    // text field 的内容
    NSString *contentText = textView.text;
    
    // 获取高亮内容的范围
    UITextRange *selectedRange = [textView markedTextRange];
    // 这行代码 可以认为是 获取高亮内容的长度
    NSInteger markedTextLength = [textView offsetFromPosition:selectedRange.start toPosition:selectedRange.end];
    // 没有高亮内容时,对已输入的文字进行操作
    if (markedTextLength == 0) {
        // 如果 text field 的内容长度大于我们限制的内容长度
        if (contentText.length > maxLength) {
            NSRange rangeRange = [contentText rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
            textView.text = [contentText substringWithRange:rangeRange];
        }
    }
}
复制代码

Guess you like

Origin blog.csdn.net/weixin_33984032/article/details/91392068