1. 程式人生 > >iOS UITextView placeHolder佔位文字的N種方法實現方法

iOS UITextView placeHolder佔位文字的N種方法實現方法

方法一

1.把UITextView的text屬性當成“placeholder”使用。
2.在開始編輯的代理方法裡清除“placeholder”。
3.在結束編輯的代理方法里根據條件設定“placeholder”。

特點:這種方法的特點是,當用戶點選了textView,placeholder佔位文字就會立馬消失,官方的placeholder是當系統監聽到使用者輸入了文字後placeholder才會消失。

// 建立textView
UITextView *textView =[[UITextViewalloc]initWithFrame:CGRectMake(20,70,SCREEN.width-40,100)]; textView.backgroundColor= [UIColor whiteColor]; textView.text = @"我是placeholder"; textView.textColor = [UIColor grayColor]; textView.delegate = self; [self.view addSubview:textView]; #pragma mark - UITextViewDelegate - (void)textViewDidEndEditing:(UITextView *)textView { if(textView.text.length < 1){ textView.text = @"我是placeholder"; textView.textColor = [UIColor grayColor]; } } - (void)textViewDidBeginEditing:(UITextView *)textView { if([textView.text isEqualToString:@"我是placeholder"]){ textView.text=@""; textView.textColor=[UIColor blackColor]; } } 

方法二

1.建立textView
2.給textView新增一個UILabel子控制元件,作為placeholder
3.在文字改變的代理方法裡面顯示/隱藏UILabel

特點:該方法同樣也可以實現類似於placeholder的功能。相比較方法一,方法二可以實現動態監聽文字的改變,並非彈出鍵盤就立即清除placeholder,只有當用戶開始輸入文字的時候。placeholder才會消失。同樣,當用戶清空文字的時候,placeholder又會重新顯示出來。

#import "WSViewController.h"

@interface WSViewController () <UITextViewDelegate> @property(nonatomic, weak)UITextView *textView; @property(nonatomic, weak)UILabel *placeHolder; @end @implementation WSViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self setupTextView]; } // 新增textView - (void)setupTextView { UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 74, SCREEN_WIDTH - 2 * 10, 200)]; textView.frame = CGRectMake(10, 74, SCREEN_WIDTH - 2 * 10, 200); [self.view addSubview:textView]; self.textView = textView; textView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0); textView.delegate = self; [self setupPlaceHolder]; //在彈出的鍵盤上面加一個view來放置退出鍵盤的Done按鈕 UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)]; [topView setBarStyle:UIBarStyleDefault]; UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)]; NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil]; [topView setItems:buttonsArray]; [textView setInputAccessoryView:topView]; } // 給textView新增一個UILabel子控制元件 - (void)setupPlaceHolder { UILabel *placeHolder = [[UILabel alloc] initWithFrame:CGRectMake(15, -2, SCREEN_WIDTH - 2 * 15, 200)]; self.placeHolder = placeHolder; placeHolder.text = @"我是placeholder"; placeHolder.textColor = [UIColor lightGrayColor]; placeHolder.numberOfLines = 0; placeHolder.contentMode = UIViewContentModeTop; [self.textView addSubview:placeHolder]; } #pragma mark - UITextViewDelegate - (void)textViewDidChange:(UITextView *)textView { if (!textView.text.length) { self.placeHolder.alpha = 1; } else { self.placeHolder.alpha = 0; } } //關閉鍵盤 -(void) dismissKeyBoard{ [self.textView resignFirstResponder]; } @end 

同樣地思路,我們也可以把作為佔位文字的UILabel用UITextField或者UITextView來替換,同樣可以實現帶placeholder的textView,在次就不在詳述。

方法三

1.自定義UITextView
2.給UITextView新增placeholder和placeholderColor屬性
3.重寫initWithFrame方法
4.新增通知監聽文字改變
5.重寫drawRect:方法
6.重寫相關屬性的set方法

特點:相比計較上面兩種方法,這種方法可移植性、拓展性更好,這種方法,不僅樂意隨意通過我們新增的placeholder屬性設定預設文字,還可以通過我們新增的placeholderColor設定預設文字的顏色。今後,我們只需要寫好這麼一個自定義UITextView,就可以一勞永逸。

#import <UIKit/UIKit.h>

@interface WSPlaceholderTextView : UITextView /** 佔位文字 */ @property (nonatomic, copy) NSString *placeholder; /** 佔位文字顏色 */ @property (nonatomic, strong) UIColor *placeholderColor; @end #import "WSPlaceholderTextView.h" @implementation WSPlaceholderTextView - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // 設定預設字型 self.font = [UIFont systemFontOfSize:15]; // 設定預設顏色 self.placeholderColor = [UIColor grayColor]; // 使用通知監聽文字改變 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self]; } return self; } - (void)textDidChange:(NSNotification *)note { // 會重新呼叫drawRect:方法 [self setNeedsDisplay]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } /** * 每次呼叫drawRect:方法,都會將以前畫的東西清除掉 */ - (void)drawRect:(CGRect)rect { // 如果有文字,就直接返回,不需要畫佔位文字 if (self.hasText) return; // 屬性 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSFontAttributeName] = self.font; attrs[NSForegroundColorAttributeName] = self.placeholderColor; // 畫文字 rect.origin.x = 5; rect.origin.y = 8; rect.size.width -= 2 * rect.origin.x; [self.placeholder drawInRect:rect withAttributes:attrs]; } - (void)layoutSubviews { [super layoutSubviews]; [self setNeedsDisplay]; } #pragma mark - setter - (void)setPlaceholder:(NSString *)placeholder { _placeholder = [placeholder copy]; [self setNeedsDisplay]; } - (void)setPlaceholderColor:(UIColor *)placeholderColor { _placeholderColor = placeholderColor; [self setNeedsDisplay]; } - (void)setFont:(UIFont *)font { [super setFont:font]; [self setNeedsDisplay]; } - (void)setText:(NSString *)text { [super setText:text]; [self setNeedsDisplay]; } - (void)setAttributedText:(NSAttributedString *)attributedText { [super setAttributedText:attributedText]; [self setNeedsDisplay]; } @end 

方法四

1.自定義UITextView
2.給UITextView新增placeholder和placeholderColor屬性
3.重寫initWithFrame方法
4.重寫drawRect:方法
5.重寫相關屬性的set方法

特點:這個方法的和方法三很相似,只是沒有利用通知來監聽文字的改變,需要配合textViewDidChanged:這個文字改變的代理方法使用。

#import <UIKit/UIKit.h>

@interface WSTextView : UITextView /** 佔位文字 */ @property (nonatomic,copy) NSString *placeholder; /** 佔位文字顏色 */ @property (nonatomic,strong) UIColor *placeholderColor; @end #import "WSTextView.h" @implementation WSTextView - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { self.font = [UIFont systemFontOfSize:15]; self.placeholderColor = [UIColor lightGrayColor]; self.placeholder = @"請輸入內容"; } return self; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSFontAttributeName] = self.font; attrs[NSForegroundColorAttributeName] = self.placeholderColor; [self.placeholder drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) withAttributes:attrs]; } // 佈局子控制元件的時候需要重繪 - (void)layoutSubviews { [super layoutSubviews]; [self setNeedsDisplay]; } // 設定屬性的時候需要重繪,所以需要重寫相關屬性的set方法 - (void)setPlaceholder:(NSString *)placeholder { _placeholder = placeholder; [self setNeedsDisplay]; } - (void)setPlaceholderColor:(UIColor *)placeholderColor { _placeholderColor = placeholderColor; [self setNeedsDisplay]; } - (void)setFont:(UIFont *)font { [super setFont:font]; [self setNeedsDisplay]; } - (void)setText:(NSString *)text { [super setText:text]; if (text.length) { // 因為是在文字改變的代理方法中判斷是否顯示placeholder,而通過程式碼設定text的方式又不會呼叫文字改變的代理方法,所以再此根據text是否不為空判斷是否顯示placeholder。 self.placeholder = @""; } [self setNeedsDisplay]; } - (void)setAttributedText:(NSAttributedString *)attributedText { [super setAttributedText:attributedText]; if (attributedText.length) { self.placeholder = @""; } [self setNeedsDisplay]; } @end // 應用的時候需要配合UITextView的文字改變的代理方法 #import "ViewController.h" #import "WSTextView.h" @interface ViewController ()<UITextViewDelegate> // @property(nonatomic,weak) WSTextView *textView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { WSTextView *textView = [[WSTextView alloc] initWithFrame:CGRectMake(10, 20, self.view.frame.size.width, 30)]; textView.placeholder = @"ws"; textView.delegate = self; [self.view addSubview:textView]; // textView.text = @"試試會不會呼叫文字改變的代理方法"; // 不會呼叫文字改變的代理方法 textView.attributedText = [[NSAttributedString alloc] initWithString:@"富文字"]; // self.textView = textView; } #pragma mark - UITextViewDelegate - (void)textViewDidChange:(WSTextView *)textView // 此處取巧,把代理方法引數型別直接改成自定義的WSTextView型別,為了可以使用自定義的placeholder屬性,省去了通過給控制器WSTextView型別屬性這樣一步。 { if (textView.hasText) { // textView.text.length textView.placeholder = @""; } else { textView.placeholder = @"ws"; } } @end 

方法五

通過runtime,我們發現,UITextView內部有一個名為“_placeHolderLabel”的私有成員變數。大家知道,Objective-C沒有絕對的私有變數,因為我們可以通過KVC來訪問私有變數。

特點:相對於上面的4種方法,這種方法更加取巧,雖然Apple官方沒有給我們開發者提供類似於placeholder的屬性,但是通過執行時,我們遍歷出了一個placeHolderLabel的私有變數。這種方法簡單易懂,程式碼量少,推薦大家使用這種方法。

#import "ViewController.h"
#import <objc/runtime.h>
#import <objc/message.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad];   // 通過執行時,發現UITextView有一個叫做“_placeHolderLabel”的私有變數 unsigned int count = 0; Ivar *ivars = class_copyIvarList([UITextView class], &count); for (int i = 0; i < count; i++) { Ivar ivar = ivars[i]; const char *name = ivar_getName(ivar); NSString *objcName = [NSString stringWithUTF8String:name]; NSLog(@"%d : %@",i,objcName); } [self setupTextView]; } - (void)setupTextView { UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 100]; [textView setBackgroundColor:[UIColor greenColor]]; [self.view addSubview:textView]; // _placeholderLabel UILabel *placeHolderLabel = [[UILabel alloc] init]; placeHolderLabel.text = @"請輸入內容"; placeHolderLabel.numberOfLines = 0; placeHolderLabel.textColor = [UIColor lightGrayColor]; [placeHolderLabel sizeToFit]; [textView addSubview:placeHolderLabel]; // same font textView.font = [UIFont systemFontOfSize:13.f]; placeHolderLabel.font = [UIFont systemFontOfSize:13.f]; [textView setValue:placeHolderLabel forKey:@"_placeholderLabel"]; } @end