iOS 关于限制字数输入的效果,so seay

作者: Wo的小名叫单纯 | 来源:发表于2016-06-08 14:39 被阅读215次

    h文件
    //输入文字的textview
    @property(nonatomic,strong)UITextView *textView;
    //计算字数的laebl
    @property(nonatomic,strong)UILabel *zishuLabel;
    记得添加textview的代理: UITextViewDelegate

    m文件
    分别定义 textview 和 label
    //textview
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 60, self.view.bounds.size.width - 20, 200)];
    self.textView.layer.cornerRadius = 5;
    self.textView.layer.borderColor = [UIColor blackColor].CGColor;
    self.textView.layer.borderWidth = 1;
    self.textView.delegate = self;
    [self.view addSubview:_textView];

    //label
    self.zishuLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 110, 230, 100, 30)];
    self.zishuLabel.text = @"0/100";
    [self.view addSubview:_zishuLabel];

    写关于textview的代理方法
    -(void)textViewDidChange:(nonnull UITextView *)textView
    {
    self.zishuLabel.text = [NSString stringWithFormat:@"%ld/100",textView.text.length];

    NSInteger res = 100-textView.text.length;
    if(res >= 0){
        
    }else{
        self.textView.text = [self.textView.text substringToIndex:100];
        self.zishuLabel.text = @"100/100";
    }
    

    }
    -(BOOL)textView:(UITextView )textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString)text
    {
    if ([text isEqualToString:@"\n"]) {
    [self.textView resignFirstResponder];
    return NO;
    }
    return YES;
    }

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {

    [self.textView resignFirstResponder];
    
    return YES;
    

    }

    好了,完成了!

    相关文章

      网友评论

        本文标题:iOS 关于限制字数输入的效果,so seay

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