限制UITextView的输入字数
要实现UITextView的输入字数限制需要遵守<UITextViewDelegate>
协议,然后在其字符变化触发的代理方法中做限制操作
//需要限制输入字数的textView,以下已250字为例
@property (weak, nonatomic) IBOutlet UITextView *textView;
//添加一个显示字数的label
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
- (void)viewDidLoad {
[super viewDidLoad];
self.textView.delegate = self;
self.countLabel.text = [NSString stringWithFormat:@"%lu/250",(unsigned long)self.textView.text.length];
}
//在代理方法中做限制
- (void)textViewDidChange:(UITextView *)textView{
//字数改变时同事改变label显示的字数
self.countLabel.text = [NSString stringWithFormat:@"%lu/250",(unsigned long)self.textView.text.length];
//当超过限制字数时,label显示的字数为250,同时截取多余的输入字符
if (textView.text.length > 250){
self.countLabel.text = [NSString stringWithFormat:@"250/250"];
textView.text = [textView.text substringToIndex:250];
}
}
还没有评论,来说两句吧...