DeveKing7-給UITextView新增Placeholder最簡單易懂的方法
今天專案裡又需要寫一個有佔位符的UITextView控制元件,以前的話都是用代理來判斷實現的,每個類裡都需要判斷,太麻煩了,所以為了便於以後再次用到需要佔位符的UITextView,決定自己寫一個自定義的UITextView,首先我想到的就是繼承。網上也有很多利用分類Categories的方法,利用runtime和新增的UILabel控制元件來做這個佔位符效果實在有點大智若愚。故自己寫了一個,程式碼很簡單,
.h檔案
#import <UIKit/UIKit.h>
@interface WLTUITextView : UITextView
-(void)setPlaceholder:(
@end
.m檔案
#import "WLTUITextView.h"
@implementation WLTUITextView{
NSString * placheolder;
UIColor * _placeholderColor;
}
-(void)setPlaceholder:(NSString *)str and:(UIColor *)color{
_placeholderColor = color;
placheolder = str;
self
self.textColor = _placeholderColor?_placeholderColor:[UIColorgrayColor];
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(textDidBegin) name:UITextViewTextDidBeginEditingNotificationobject:self];
[[NSNotificationCenterdefaultCenter] addObserver:self
//這裡使用KVO時,會出現死迴圈,因為佔位符的邏輯問題。所以這裡不適合用KVO 故採用以上的方法更簡單。網上的那些使用runtime機制又加了label來做佔位符的方法實在是有點大智若愚的感覺。我覺得用最簡單的程式碼解決複雜問題的能力就是一個人的邏輯思維能力。
}
-(void)textDidBegin{
if ([self.textisEqualToString:placheolder]) {
self.text = @"";
self.textColor = [UIColorblackColor];
}
}
-(void)textDidEnd{
if([self.textisEqualToString:@""]){
self.text = placheolder;
self.textColor = _placeholderColor?_placeholderColor:[UIColorgrayColor];
}
}