一.设置占位文字的颜色
方法一:利用富文本
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
- (void)viewDidLoad { [super viewDidLoad]; NSMutableDictionary *attributes = [NSMutableDictionary dictionary]; attributes[NSForegroundColorAttributeName] = [UIColor whiteColor]; self.phoneTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"手机号" attributes:attributes]; }
|
方法二:利用Runtime
获取私有的属性名称,利用KVC
设置属性
1 2
| // 设置占位文字的颜色为红色(注意下面的'self'代表你要修改占位文字的UITextField控件) [self setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
|
- 注意:
_placeholderLabel.textColor
是不可乱写的哦,我们是怎么获取到这个属性的呢?请看下文:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| + (void)initialize {
[self getIvars]; }
+ (void)getIvars { unsigned int count = 0; Ivar *ivars = class_copyIvarList([UITextField class], &count); for (int i = 0; i < count; i++) { Ivar ivar = ivars[i]; NSLog(@"%s----%s", ivar_getName(ivar), ivar_getTypeEncoding(ivar)); } }
|
查看打印,找出可能的属性名称,试试便知;
- 完整代码:自定义的
UITextField
,获取到焦点(编辑状态)的时候是白色,失去焦点(非编辑状态)的时候是灰色:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #import "YCTextField.h" #import <objc/runtime.h>
#define YCplaceholderTextColor @"_placeholderLabel.textColor"
@implementation YCTextField
+ (void)initialize {
[self getIvars]; }
+ (void)getIvars { unsigned int count = 0; Ivar *ivars = class_copyIvarList([UITextField class], &count); for (int i = 0; i < count; i++) { Ivar ivar = ivars[i]; NSLog(@"%s----%s", ivar_getName(ivar), ivar_getTypeEncoding(ivar)); } }
- (void)awakeFromNib {
self.tintColor = self.textColor; }
- (BOOL)becomeFirstResponder {
[self setValue:self.textColor forKeyPath:YCplaceholderTextColor]; return [super becomeFirstResponder]; }
- (BOOL)resignFirstResponder {
[self setValue:[UIColor grayColor] forKeyPath:YCplaceholderTextColor]; return [super resignFirstResponder]; }
@end
|
方法三.将占位文字画
上去(重写- (void)drawPlaceholderInRect:(CGRect)rect;
)
1 2 3 4 5 6
| - (void)drawPlaceholderInRect:(CGRect)rect {
[[UIColor orangeColor] set]; [self.placeholder drawInRect:rect withFont:[UIFont systemFontOfSize:20]]; }
|
二.设置光标颜色
1 2
| self.tintColor = [UIColor redColor];
|
三.设置占位文字的偏移
- 重写
-(CGRect)placeholderRectForBounds:(CGRect)bounds;
方法
- 可以用来设置光标与占位的间距
1 2 3 4 5 6 7
| -(CGRect)placeholderRectForBounds:(CGRect)bounds {
CGRect inset = CGRectMake(bounds.origin.x+50, bounds.origin.y, bounds.size.width -10, bounds.size.height); return inset; }
|
- 扩充:系统还提供了很多类似的方法
- 重写来重置文字区域
- 重写来重置文字区域
- 改变绘文字属性.重写时调用super
- 重写来重置占位符区域
1
| – placeholderRectForBounds:
|
- 重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用
1
| – drawPlaceholderInRect:
|
- 重写来重置边缘区域
- 重写来重置编辑区域
- 重写来重置clearButton位置,改变size可能导致button的图片失真
1
| – clearButtonRectForBounds:
|
- leftView Bounds
1
| – leftViewRectForBounds:
|
- rightView Bounds
1
| – rightViewRectForBounds:
|