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 }

 

posted @ 2017-04-05 14:29  Accepted.DXY  阅读(1485)  评论(0编辑  收藏  举报