UITextField在iOS中将占位符颜色设置为暗色
问题描述:
我试图将 UITextField
占位符颜色设置为暗。
I have tried to set UITextField
"Placeholder" color as dark.
NSAttributedString * search = [[NSAttributedString alloc] initWithString:@"Search" attributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
textField.attributedPlaceholder = search;
-
但仍然
UITextField
在占位符中显示浅灰色。是否可以设置深色占位符
UITextField
的颜色?Is it possible to set dark "placeholder" color for
UITextField
?另外我也尝试了另一种方法
Also I Have tried the another method as well
[textField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
但这两种方法都适用于 iOS 7 ,但不能正常工作 iOS 6 。
But both methods are working in iOS 7, But not working on iOS 6.
- 是否可以为占位符颜色 iOS 6 目标中的code> UITextField ?
- Is it possible to set dark "placeholder" color for
UITextField
in iOS 6 target?
谢谢!
答
正如Apple建议的那样,继承UITextField并覆盖 - (void)drawPlaceholderInRect:(CGRect)rect
是要走的路:
As suggested by Apple, subclassing UITextField and overriding - (void)drawPlaceholderInRect:(CGRect)rect
is the way to go:
- (void)drawPlaceholderInRect:(CGRect)rect {
UIColor *colour = [UIColor lightGrayColor];
if ([self.placeholder respondsToSelector:@selector(drawInRect:withAttributes:)])
{ // iOS7 and later
NSDictionary *attributes = @{NSForegroundColorAttributeName: colour, NSFontAttributeName: self.font};
CGRect boundingRect = [self.placeholder boundingRectWithSize:rect.size options:0 attributes:attributes context:nil];
[self.placeholder drawAtPoint:CGPointMake(0, (rect.size.height/2)-boundingRect.size.height/2) withAttributes:attributes]; }
else { // iOS 6
[colour setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:NSLineBreakByTruncatingTail alignment:self.textAlignment];
}
}