GuaGuaiOS UI相关知识

iOS开发之设置UITextField的占位文字颜色三种方式

2016-11-14  本文已影响1176人  一个很帅的蓝孩子
设置UITextField的占位文字颜色三种方式

1>KVC修改 如果不先设置占位文字, 占位文字的颜色是不管用的:

UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
textField.placeholder = @"设置了占位文字内容以后, 才能设置占位文字的颜色";
textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

2>通过attributedPlaceholder属性修改占位文字颜色

CGFloat viewWidth  = self.view.bounds.size.width;****
CGFloat textFieldX = 50;
CGFloat textFieldH = 30;
CGFloat padding    = 30;
UITextField *textField = [[UITextField alloc] init];
textField.frame = CGRectMake(textFieldX, 100, viewWidth - 2 * textFieldX, textFieldH);
textField.borderStyle = UITextBorderStyleRoundedRect; // 边框类型
textField.font = [UIFont systemFontOfSize:14];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入占位文字" attributes:
@{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:textField.font
}];
textField.attributedPlaceholder = attrString;
[self.view addSubview:textField];

3>通过重写UITextField的drawPlaceholderInRect:方法修改占位文字颜色

步骤:
-(void)drawPlaceholderInRect:(CGRect)rect {
// 计算占位文字的 Size
CGSize placeholderSize = [self.placeholder sizeWithAttributes:
@{NSFontAttributeName : self.font}];
[self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes:
@{NSForegroundColorAttributeName : [UIColor blueColor],
NSFontAttributeName : self.font}];
}
上一篇 下一篇

猜你喜欢

热点阅读