屏幕快照 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;
}