textField開始編輯和結束編輯後佔位文字顏色的設定

weixin_33890499發表於2017-09-10

需求:一般會要求設定點選開始編輯後佔位文字的顏色

理論指導:

1.一旦見到控制元件上的點選事件,馬上想到監聽,一見到監聽,馬上想到讓代理物件或者target物件去監聽,一見到代理物件,馬上想到在非控制元件類中去設定代理,控制元件類中是不允許自己設定自己為代理的,如:self.delegate = self 代理產生背景就是由於自己不想做的事情交給別人來做,在自己類中自己監聽自己只能用addTarget去做

2.textField上有兩個事件,點選開始編輯和點選其他地方結束編輯,addTarget是解決這樣的事件最好的方法

3.textField是繼承於UIControl,可以用addTarget

解決方法:

1.設定富文字顏色屬性

[self addTarget:self action:@selector(editBegin) forControlEvents:UIControlEventEditingDidBegin];

[self addTarget:self action:@selector(editEnd) forControlEvents:UIControlEventEditingDidEnd];

NSMutableDictionary *attrs = [NSMutableDictionary dictionary];

attrs[NSForegroundColorAttributeName] = [UIColor lightGrayColor];

self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrs];

2.拿到佔位文字label,直接設定它的color

由於佔位文字label是textField的私有屬性,所以正常是拿不到的,只能藉助於kvc

根據成員變數名獲取到該控制元件物件

UILabel *placeHolderLabel = [self valueForKey:@"placeHolderLabel"];

placeHolderLabel.textColor = [UIColor whiteColor];

注意:儘管這樣使用比較簡單,但是我還是傾向於使用第一種方法

封裝:

由於testField沒有直接提供placeHolderColor屬性,而我們為了仿照系統控制元件其它屬性可以這樣直接點出來,所以進行一個封裝,封裝到哪裡呢?這就要進行分析,這個屬性是不是所有的textField控制元件都要使用,如果都要使用,那麼封裝到分類中

1.先在.h中宣告屬性,分類中的屬性不會形成set和get實現,只會生成宣告

@property UIColor *placeHolderColor;

2.在.m中實現set和get方法

-(void)setPlaceHolderColor:(UIColor *)placeHolderColor

{

NSMutableDictionary *attrs = [NSMutableDictionary dictionary];

attrs[NSForegroundColorAttributeName] = placeHolderColor;

self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrs];

}

-(UIColor *)placeHolderColor

{

return nil;

}

相關文章