UITextField在iOS中将占位符颜色设置为暗色

前端之家收集整理的这篇文章主要介绍了UITextField在iOS中将占位符颜色设置为暗色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将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]; 
    } 
 }

信用:http://www.brightec.co.uk/blog/how-change-colour-uitextfields-placeholder-text-ios7-and-still-support-ios6

原文链接:/iOS/334154.html

猜你在找的iOS相关文章