- 修改UITextField占位文字顏色常用方法
- 1.通過富文本
- 2.通過Runtime私有的屬性,利用KVC設(shè)置屬性
- 3.通過
- (void)drawPlaceholderInRect:(CGRect)rect畫上去
-詳情參考YotrolZ的UITextField-修改占位文字和光標(biāo)的顏色,大小

Simulator Screen Shot 2016年1月23日 下午7.42.39.png
在這里我通過給UITextField添加分類 提供"placeholderColor"屬性直接在添加UITextField時使用
- 具體代碼實現(xiàn)
#import <UIKit/UIKit.h>
@interface UITextField (Extension)
/** 占位文字顏色 */
@property(nonatomic, strong) UIColor *placeholderColor;
@end
在這里只會生成placeholderColor的setter和gettet方法的聲明,不會生成方法的實現(xiàn)和_成員變量
#import "UITextField+Extension.h"
@implementation UITextField (Extension)
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
BOOL change = NO;
//保證有占位文字
if (self.placeholder == nil) {
self.placeholder = @" ";
change = YES;
}
//設(shè)置占位文字顏色
[self setValue:placeholderColor forKeyPath:@"placeholderLabel.textColor"];
//恢復(fù)原狀
if (change) {
self.placeholder = nil;
}
}
-(UIColor *)placeholderColor{
return [self valueForKey:@"placeholderLabel.textColor"];
}
@end
這里通過setter和gettet方法的的實現(xiàn)設(shè)置占位文字顏色,利用的Runtime私有屬性,KVC設(shè)置屬性
- Runtime運行時的使用 導(dǎo)入頭文件
#import <objc/runtime.h>
unsigned int outCount = 0;
Ivar *var = class_copyIvarList([UITextField class], &outCount);
for (int i = 0; i < outCount; i++) {
Ivar ivar = var[i];
NSLog(@"%s", ivar_getName(ivar));
}
free(var);
通過以上代碼就可以拿到私有的成員屬性

hu.jpg