美文网首页
textField 与 textview字数限制

textField 与 textview字数限制

作者: 沬日十七 | 来源:发表于2018-03-01 11:30 被阅读0次

-(BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string

{

    NSString* tostring = [textField.textstringByReplacingCharactersInRange:rangewithString:string];

    UITextRange*selectedRange = [textFieldmarkedTextRange];

    UITextPosition*position = [textFieldpositionFromPosition:selectedRange.startoffset:0];

    if(!position){

        NSIntegercharlen = tostring.length;

        if(charlen>1)

        {

            if(![XYStringisBlankString:string]) {

                returnNO;

            }

        }

    }

    return YES;

}

#pragma mark - TextView代理方法

-(BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text

{

    NSString*str = [NSStringstringWithFormat:@"%@%@", textView.text, text];

    if(str.length>100)

    {

        NSRange rangeIndex = [str rangeOfComposedCharacterSequenceAtIndex:100];

        if(rangeIndex.length==1)//字数超限

        {

            textView.text= [strsubstringToIndex:100];

            self.testNumLb.text=@"100/100";

        }else{

            NSRange rangeRange = [str rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 100)];

            textView.text= [strsubstringWithRange:rangeRange];

        }

        returnNO;

    }

    return YES;

}

-(void)textViewDidChange:(UITextView*)textView

{

    self.testNumLb.text= [NSStringstringWithFormat:@"%lu/%d", (unsignedlong)textView.text.length,100];

}

相关文章

网友评论

      本文标题:textField 与 textview字数限制

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