iOS 给UITextView加一个placeholder

苹果并没有为UITextView提供placeholder功能。我们可以通过两种办法实现。

方法一:

思路:设置默认显示的文字,颜色设置为灰色。代理方法监听textView的开始编辑和结束编辑时候的字数。

缺点:如果点击到文字上的时候,光标不会出现在textView的一开始的地方。和原生placeholder不同。

1         _contentText = [[UITextView alloc] init];
2         _contentText.text = @"请输入您的反馈";
3         _contentText.textColor = [UIColor grayColor];
4         _contentText.delegate = self;    

遵守<UITextViewDelegate>实现方法

 1 - (void)textViewDidEndEditing:(UITextView *)textView
 2 {
 3     if(textView.text.length < 1){
 4         self.contentText.text = @"请输入您的反馈";
 5         self.contentText.textColor = [UIColor grayColor];
 6     }
 7 }
 8 - (void)textViewDidBeginEditing:(UITextView *)textView
 9 {
10     if([self.contentText.text isEqualToString:@"请输入您的反馈"]){
11         self.contentText.text=@"";
12         self.contentText.textColor=[UIColor blackColor];
13     }
14 }

 

方法二:

思路:给textView上加一个UILabel。放到适当的位置。监听输入框文字改变,改变label的alpha

1 #pragma mark - 监听输入框
2 - (void)textViewDidChange:(UITextView *)textView{
3     if (!self.contentText.text.length) {
4         self.placeHolderLabel.alpha = 1;
5     }else{
6         self.placeHolderLabel.alpha = 0;
7     }
8 }

 

转载于:https://www.cnblogs.com/wronganswer/p/6668586.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值