今天項目里又需要寫一個有占位符的UITextView控件榴徐,以前的話都是用代理來判斷實現(xiàn)的冠王,每個類里都需要判斷澄暮,太麻煩了月帝,所以為了便于以后再次用到需要占位符的UITextView,決定自己寫一個自定義的UITextView,首先我想到的就是繼承。網(wǎng)上也有很多利用分類Categories的方法红氯,利用runtime和新增的UILabel控件來做這個占位符效果實在有點大智若愚框咙。故自己寫了一個,代碼很簡單痢甘,
.h文件
#import?
@interface?WLTUITextView :?UITextView
-(void)setPlaceholder:(NSString?*)str and:(UIColor?*)color;
@end
.m文件
#import?"WLTUITextView.h"
@implementation?WLTUITextView{
?NSString?* placheolder;
?UIColor?* _placeholderColor;
}
-(void)setPlaceholder:(NSString?*)str and:(UIColor?*)color{
?_placeholderColor?= color;
?placheolder?= str;
?self.text?= str;
?self.textColor?=?_placeholderColor?_placeholderColor:[UIColor?grayColor];
? ? [[NSNotificationCenter?defaultCenter]?addObserver:self?selector:@selector(textDidBegin)?name:UITextViewTextDidBeginEditingNotification?object:self];
? ? [[NSNotificationCenter?defaultCenter]?addObserver:self?selector:@selector(textDidEnd)?name:UITextViewTextDidEndEditingNotification?object:self];
?//這里使用KVO時喇嘱,會出現(xiàn)死循環(huán),因為占位符的邏輯問題塞栅。所以這里不適合用KVO?故采用以上的方法更簡單婉称。網(wǎng)上的那些使用runtime機(jī)制又加了label來做占位符的方法實在是有點大智若愚的感覺。我覺得用最簡單的代碼解決復(fù)雜問題的能力就是一個人的邏輯思維能力。
}
-(void)textDidBegin{
?if?([self.text?isEqualToString:placheolder]) {
?self.text?=?@"";
?self.textColor?= [UIColor?blackColor];
? ? }
}
-(void)textDidEnd{
?if([self.text?isEqualToString:@""]){
?self.text?=?placheolder;
?self.textColor?=?_placeholderColor?_placeholderColor:[UIColor?grayColor];
? ? }
}