美文网首页
textView对字数进行限制处理

textView对字数进行限制处理

作者: 向晚forever | 来源:发表于2017-01-06 17:33 被阅读34次
屏幕快照 2017-01-06 下午5.34.33.png

要实现这种效果
1、文本数据肯定不能覆盖到下面的字数提示。
2、粘贴也要能保证字数正确,切掉多了的数字。
我的这个控件是四部分组成:背景view,titleLab,textView,numberLab。必须要用textView的,textField有它的局限性。达不到产品的要求。

textView的代理实现:

- (void)textViewDidChange:(UITextView *)textView
{
    NSMutableString *content = [NSMutableString stringWithString:textView.text];
    if ([[XgTool sharedXgTool] isString:content]) {
        commentTextView.enablesReturnKeyAutomatically = YES; //这里设置为无文字就灰色不可点
    }
    else{
        commentTextView.enablesReturnKeyAutomatically = NO;
    }
    
    if (textView.text.length > 140) {
        //当字数大于140就切掉多余的字
        textView.text = [textView.text substringToIndex:140];
        commentTextView.enablesReturnKeyAutomatically = YES; //当字数超过140时return不能点击
    }

    textLenthLab.text = [NSString stringWithFormat:@"%lu/140",(unsigned long)textView.text.length];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (textView.text.length > 140) {
        return NO;
    }
    else{
        textLenthLab.text = [NSString stringWithFormat:@"%lu/140",(unsigned long)textView.text.length];
    }
    //判断是否为删除字符,如果为删除则让执行
    char c=[text UTF8String][0];
    if (c=='\000') {
        textLenthLab.text=[NSString stringWithFormat:@"%u/140",[[textView text] length] - 1];
        return YES;
    }
    
    if([[textView text] length]==141) {//我们项目是140字,这里要为141不然按return不会响应因为return也是一个字符
        if(![text isEqualToString:@"\b"]) return NO;
    }
    
    textLenthLab.text=[NSString stringWithFormat:@"%u/140",textView.text.length];
    
    return YES;
    
}

相关文章

网友评论

      本文标题:textView对字数进行限制处理

      本文链接:https://www.haomeiwen.com/subject/yjkxbttx.html