textView對字數進行限制處理

屏幕快照 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;
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容