简体   繁体   English

iPhone UITextField - 更改占位符字体和文本颜色

[英]iPhone UITextField - Change placeholder Font and Text Color

I have a UITextField where i need to change the Placeholder Font and Color, i'm calling the below method in drawRect method, 我有一个UITextField ,我需要更改Placeholder字体和颜色,我在drawRect方法中调用下面的方法,

-(void) setFontColorForPlaceHolder
{
    for(id obj in [[self baseScrollView] subviews])
    {
        if([obj isKindOfClass:[UITextField class]])
        {
            [obj setAttributedPlaceholder:[[NSAttributedString alloc]initWithString:[obj placeholder] attributes:@{
                NSFontAttributeName:kFutura_Medium_14 ,NSForegroundColorAttributeName:[UIColor redColor]
            }]];
        }
    }
}

Here the COLOR is changing but the FONT is not setting. 这里的颜色正在变化但是FONT没有设置。 What is the issue here with setAttributedPlaceholder . setAttributedPlaceholder什么问题。

I was testing in iOS 7.1 and found out that NSFontAttributeName isn't doing anything to UITextField 's placeholder text. 我在iOS 7.1中测试,发现NSFontAttributeName没有对UITextField的占位符文本做任何事情。

However, when I changed the font of the UITextField itself, the placeholder text font changed as well: 但是,当我更改UITextField本身的字体时,占位符文本字体也会更改:

aUITextField.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:20.0f];

For iOS 6+ 适用于iOS 6+

[textField setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];

To set a font for placeholder, just set a font for textfield before writing textholder. 要设置占位符的字体,只需在编写textholder之前为textfield设置字体。

textField.font = your font here;
[textField setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
textField.placeholder = "your placeholder string here...";

SWIFT 3 In your custom class override this: SWIFT 3在您的自定义类中重写此:

override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
     //set initial attributed placeholder color and font
     self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: placeholderColor, NSFontAttributeName: placeholderTextFont])
     return bounds
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM