美文网首页
UItextFiled和UITextView 限制字数

UItextFiled和UITextView 限制字数

作者: 路边的风景呢 | 来源:发表于2018-07-05 17:06 被阅读12次

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;

    }

}

比较简单  

相关文章

网友评论

      本文标题:UItextFiled和UITextView 限制字数

      本文链接:https://www.haomeiwen.com/subject/uxgpuftx.html