Skip to content

Instantly share code, notes, and snippets.

@Mephsito23
Created February 22, 2019 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mephsito23/e9280bcb3672be2c00ba2f0d31f5889e to your computer and use it in GitHub Desktop.
Save Mephsito23/e9280bcb3672be2c00ba2f0d31f5889e to your computer and use it in GitHub Desktop.
UITextField的Placeholder颜色的三种方式
//第一种
UITextField *textField = [[UITextField alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入占位文字"
attributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:textField.font}];
textField.attributedPlaceholder = attrString;
//第二种
UITextField *textField1 = [[UITextField alloc] init];
textField1.placeholder = @"请输入占位文字";
textField1.font = [UIFont systemFontOfSize:14];
// "通过KVC修改占位文字的颜色"
[textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.view addSubview:textField1];
//第三种
// 重写此方法
-(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 redColor],
NSFontAttributeName : self.font}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment