效果圖atom
程序以下:code
方法一:orm
@property (nonatomic, copy) void(^txtViewBlock)(NSString *desTxt); - (void)awakeFromNib { [super awakeFromNib]; self.desTextView.layer.borderWidth = 1; self.desTextView.layer.borderColor = UIColorFromRGB(0xebecf0).CGColor; self.desTextView.layer.masksToBounds = YES; self.desTextView.delegate = self; //設置通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTextView:) name:UITextViewTextDidChangeNotification object:nil]; // Initialization code } - (void)changeTextView:(id)sender { if (_txtViewBlock) { _txtViewBlock(self.desTextView.text); } } - (void)decription:(void (^)(NSString *))txtViewBlock { _txtViewBlock = txtViewBlock; } - (void)textViewDidChange:(UITextView *)textView { NSInteger number = [textView.text length]; if (number>0) { _placeholderLabel.hidden = YES; }else { _placeholderLabel.hidden = NO; } if (number > 255) { // UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"舒適提示" message:@"字符個數不能大於50" delegate:self cancelButtonTitle:@"肯定"otherButtonTitles:nil]; // [alert show]; textView.text = [textView.text substringToIndex:255]; number = 255; } self.textNum.text = [NSString stringWithFormat:@"%ld/255", (long)number]; }
#pragma mark -UITextViewDelegate -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ NSString *content = [textView.text stringByReplacingCharactersInRange:range withString:text]; NSInteger caninputlen = MAX_LIMIT_NUMS - content.length; if (caninputlen >= 0) { self.lengthLabel.text = [NSString stringWithFormat:@"%ld/300", (long)content.length]; if (_contentBlock) { _contentBlock(content); } return YES; } else { NSInteger len = text.length + caninputlen; //防止當text.length + caninputlen < 0時,使得rg.length爲一個非法最大正數出錯 NSRange rg = {0,MAX(len,0)}; if (rg.length > 0) { NSString *s = [text substringWithRange:rg]; content = [textView.text stringByReplacingCharactersInRange:range withString:s]; [textView setText:content]; if (_contentBlock) { _contentBlock(content); } self.lengthLabel.text = [NSString stringWithFormat:@"%ld/300", (long)content.length]; } return NO; } }