UITextField在iOS中将占位符颜色设置为暗色 [英] UITextField set placeholder color as dark in iOS

查看:138
本文介绍了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]; 
        } 
     } 
    

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

    这篇关于UITextField在iOS中将占位符颜色设置为暗色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆