我试图将UITextField“Placeholder”颜色设置为黑暗.
NSAttributedString * search = [[NSAttributedString alloc] initWithString:@"Search" attributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}]; textField.attributedPlaceholder = search;
>但是UITextField仍然在“占位符”中显示浅灰色.
>是否可以为UITextField设置深色“占位符”颜色?
我也尝试了另一种方法
[textField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
但这两种方法都适用于iOS 7,但不适用于iOS 6.
>是否可以在iOS 6目标中为UITextField设置深色“占位符”颜色?
谢谢!
解决方法
正如Apple建议的那样,继承UITextField并覆盖 – (void)drawPlaceholderInRect:(CGRect)rect是要走的路:
- (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]; } }