UITextFiled : 给输入框添加事件 下面是方法
- (void)textFieldDidChange{
NSString*toBeString =_sqsmText.text;
//获取高亮部分
UITextRange*selectedRange = [_sqsmTextmarkedTextRange];
UITextPosition*position = [_sqsmTextpositionFromPosition:selectedRange.startoffset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if(!position){
if(toBeString.length>MAX_STARWORDS_LENGTH){
UIAlertController *aletC = [UIAlertController alertControllerWithTitle:@"提示" message:@"已超出最大字数限制" preferredStyle:UIAlertControllerStyleAlert];
[aletCaddAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:aletC animated:YES completion:^{
}];
}
}
}
UITextView: 用的是代理方法
- (void)textViewDidChange:(UITextView*)textView
{
if([textView.textlength] >200) {
textView.text= [textView.textsubstringWithRange:NSMakeRange(0,200)];
[textView.undoManagerremoveAllActions];
// [textView becomeFirstResponder];
UIAlertController *aletC = [UIAlertController alertControllerWithTitle:@"提示" message:@"已超出最大字数限制" preferredStyle:UIAlertControllerStyleAlert];
[aletCaddAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:aletC animated:YES completion:^{
}];
return;
}
}
比较简单