修改占位文字顏色有四種方法:
第一種:(最簡單)一般用這個
修改內(nèi)部占位文字Label的文字顏色
[textField setValue:[UIColor grayColor] forKeyPath:@"placeholderLabel.textColor"];
第二種:使用attributedPlaceholder
// 設置占位文字內(nèi)容
@property(nullable, nonatomic,copy) NSString *placeholder;
// 設置帶有屬性的占位文字, 優(yōu)先級 > placeholder
@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder;
// 設置占位文字顏色
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attributes];
第三種:重寫- (void)drawPlaceholderInRect:(CGRect)rect;
第四種:利用分類為UITextField添加占位文字屬性--->推薦,一勞永逸
注意:
問題:為什么要先確保有占位文字,再設置占位文字顏色?
結果:若先設置占位文字顏色,在設置占位文字,就會無效果。
原因:不設置文字,就不會創(chuàng)建label這個控件,那么占位文字也就拿不到了,又如何設置占位文字顏色呢.
/** 占位文字顏色 **/
@property (nonatomic ,strong) UIColor *placeholderColor;
#import "UITextField+ZSExtension.h"
static NSString *const ZSPlaceholderColorKey = @"placeholderLabel.textColor";
@implementation UITextField (ZSExtension)
-(void)setPlaceholderColor:(UIColor *)placeholderColor
{
// 點擊時占位文字的顯示
BOOL change = NO;
//保證有占位文字
if (self.placeholder == nil) {
self.placeholder = @"";
}
// 占位文字顏色
[self setValue:placeholderColor forKeyPath:ZSPlaceholderColorKey];
// 恢復原狀
if (change) {
self.placeholderColor = nil;
}
}
-(UIColor *)placeholderColor
{
return [self valueForKeyPath:ZSPlaceholderColorKey];
}