在我們的開(kāi)發(fā)中简肴,有時(shí)候會(huì)遇到背景深色的界面上需要添加TextField晃听,TextField默認(rèn)的占位顏色也是深灰色,比較難看清砰识,這時(shí)候就需要修改展位文字的顏色能扒,可是系統(tǒng)沒(méi)有提供相應(yīng)的方法,那么就需要我們自己來(lái)自定義了辫狼,廢話不多說(shuō)初斑,下面上代碼:
// .h文件
#import <UIKit/UIKit.h>
@interface UITextField (Placeholder)
@property UIColor *placeholderColor;
@end
// .m文件
#import "UITextField+Placeholder.h"
#import <objc/message.h>
NSString * const placeholderColorName = @"placeholderColor";
@implementation UITextField (Placeholder)
+ (void)load
{
// 獲取setPlaceholder
Method setPlaceholder = class_getInstanceMethod(self, @selector(setPlaceholder:));
// 獲取bs_setPlaceholder
Method bs_setPlaceholder = class_getInstanceMethod(self, @selector(bs_setPlaceholder:));
// 交換方法
method_exchangeImplementations(setPlaceholder, bs_setPlaceholder);
}
// OC最喜歡懶加載,用的的時(shí)候才會(huì)去加載
// 需要給系統(tǒng)UITextField添加屬性,只能使用runtime
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
// 設(shè)置關(guān)聯(lián)
objc_setAssociatedObject(self,(__bridge const void *)(placeholderColorName), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// 設(shè)置占位文字顏色
UILabel *placeholderLabel = [self valueForKeyPath:@"placeholderLabel"];
placeholderLabel.textColor = placeholderColor;
}
- (UIColor *)placeholderColor
{
// 返回關(guān)聯(lián)
return objc_getAssociatedObject(self, (__bridge const void *)(placeholderColorName));
}
// 設(shè)置占位文字,并且設(shè)置占位文字顏色
- (void)bs_setPlaceholder:(NSString *)placeholder
{
// 1.設(shè)置占位文字
[self bs_setPlaceholder:placeholder];
// 2.設(shè)置占位文字顏色
self.placeholderColor = self.placeholderColor;
}
@end