修改UITextField的placeholder 字体颜色大小
2018-10-24 本文已影响0人
叫我小黑
UITextField 是 iOS 开发中常用的控件,它有一个placeholder
属性,也就是占位文字,默认占位文字颜色是70% gray
。有时,UITextField自带的Placeholder的颜色大小太浅或者不满足需求,所以需要修改,而UITextField没有直接的属性去修改Placeholder的颜色大小,所以只能通过其他间接方式去修改。
方式一
- 设置
attributedPlaceholder
属性 - 说明:此种方式对于无需动态改变placeholder颜色较为方便。
NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; // 创建属性字典
attrs[NSFontAttributeName] = [UIFont systemFontOfSize:17]; // 设置font
attrs[NSForegroundColorAttributeName] = [UIColor greenColor]; // 设置颜色
NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:@"夏虫不可以语冰" attributes:attrs]; // 初始化富文本占位字符串
self.textField.attributedPlaceholder = attStr;
方式二
- 自定义UITextField,重写
- (void)drawPlaceholderInRect:(CGRect)rect;
- 说明:此种方式只能设置一次状态,不能动态的改变placeholder的颜色,但可以设置placeholder所在位置。
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeholder drawInRect:CGRectMake(0, 2, rect.size.width, 25) withAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:16.0],
NSForegroundColorAttributeName : [UIColor blueColor],
}];
}
方式三
- 通过
KVC
修改Placeholder颜色
UITextField *textField1 = [[UITextField alloc] init];
textField1.frame = CGRectMake(textFieldX, CGRectGetMaxY(textField.frame) + padding, viewWidth - 2 * textFieldX, textFieldH);
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.placeholder = @"请输入占位文字";
textField1.font = [UIFont systemFontOfSize:14];
// "通过KVC修改占位文字的颜色"
[textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.view addSubview:textField1];