eg:
@property (nonatomic, strong) UILabel *remainLabel;
@property (nonatomic, strong) UIButton *completeBut;
// 关于View和but的配置
- (void)setUpWithKeyBoardView {
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
UIBarButtonItem *remin = [[UIBarButtonItem alloc]initWithCustomView:self.remainLabel];
UIBarButtonItem *complete = [[UIBarButtonItem alloc] initWithCustomView:self.completeBut];
NSArray * buttonsArray = [NSArray arrayWithObjects:remin,complete,nil];
[topView setItems:buttonsArray];
// 重点在这句,设置键盘的setInputAccessoryView,将按钮添加至topView
[self.infoTextview setInputAccessoryView:topView];
}
// AccessoryView
- (UILabel *)remainLabel {
if (!_remainLabel) {
_remainLabel = [[UILabel alloc] init];
_remainLabel.text = @"0/10";
_remainLabel.font = [UIFont systemFontOfSize:15.0f];
_remainLabel.textAlignment = NSTextAlignmentLeft;
_remainLabel.frame = CGRectMake(5, 0, ScreenWidth-100, 30);
}
return _remainLabel;
}
- (UIButton *)completeBut {
if (!_completeBut) {
_completeBut = [UIButton buttonWithType:UIButtonTypeCustom];
[_completeBut setTitle:@"完成" forState:UIControlStateNormal];
[_completeBut setFont:[UIFont systemFontOfSize:15.0f]];
[_completeBut addTarget:self action:@selector(completeButAction) forControlEvents:UIControlEventTouchUpInside];
[_completeBut setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
_completeBut.frame = CGRectMake(0, 0, 80, 30);
}
return _completeBut;
}
-(void)completeButAction
{
[self.infoTextview resignFirstResponder];
}
self.infoTextview.delegate = self;
// 监测一下键盘文字上的变化
- (void)textViewDidChange:(UITextView *)textView {
NSString *str = [NSString stringWithFormat:@"%ld/300",textView.text.length];
// 判断文字是否超过10个字,超过设置文字为红色
if (textView.text.length > 10) {
NSMutableAttributedString *attrDescribeStr = [[NSMutableAttributedString alloc] initWithString:str];
[attrDescribeStr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
// range:设置改变文本颜色的范围
range:[str rangeOfString:[NSString stringWithFormat:@"%ld",textView.text.length]]];
self.remainLabel.attributedText = attrDescribeStr;
} else {
self.remainLabel.text = str;
}
}