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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM