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