美文网首页
为TextView 添加 占位文字【简单】

为TextView 添加 占位文字【简单】

作者: 爱喝农药de清凉 | 来源:发表于2017-05-09 15:45 被阅读33次

    转自:http://m.2cto.com/kf/201608/534005.html

    流程:
    1.创建textView
    2.给textView添加一个UILabel子控件,作为placeholder
    3.在文本改变的代理方法里面显示/隐藏UILabel

    特点:
    该方法同样也可以实现类似于placeholder的功能。相比较方法一,方法二可以实现动态监听文本的改变,并非弹出键盘就立即清除placeholder,只有当用户开始输入文本的时候。placeholder才会消失。同样,当用户清空文本的时候,placeholder又会重新显示出来。

    代理:<UITextViewDelegate>

    pragma mark - 绘制 发布 界面

    • (void)createPublishView{

      UITextView * textView = [[UITextView alloc]init];
      self.textView = textView;
      [self.backgroundView addSubview:_textView];

      [_textView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(74);
      

      }];

      _textView.backgroundColor = [UIColor redColor];
      _textView.delegate = self;
      [self setupPlaceHolder];

    }

    // 给textView添加一个UILabel子控件

    • (void)setupPlaceHolder {
      UILabel *placeHolder = [[UILabel alloc] init];
      self.placeHolder = placeHolder;
      [self.textView addSubview:placeHolder];

      [_placeHolder mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.mas_equalTo(15);
        make.top.mas_equalTo(12);
        make.height.mas_equalTo(20);
      

      }];

      placeHolder.backgroundColor = [UIColor yellowColor];

    placeHolder.text = @"说点什么吧...";
    placeHolder.textColor = [UIColor lightGrayColor];
    placeHolder.numberOfLines = 0;
    placeHolder.contentMode = UIViewContentModeTop;
    placeHolder.font = [UIFont jk_systemFontOfPxSize:14];
    

    }

    pragma mark - TextView 代理 & 数据源

    • (void)textViewDidChange:(UITextView *)textView {
      if (!textView.text.length) {
      self.placeHolder.alpha = 1;
      } else {
      self.placeHolder.alpha = 0;
      }
      }
      //关闭键盘
      -(void) dismissKeyBoard{

      [self.textView resignFirstResponder];

    }

    相关文章

      网友评论

          本文标题:为TextView 添加 占位文字【简单】

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