ios 如何在保留其现有属性的同时为 UITextField 设置占位符文本的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18584587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:57:11  来源:igfitidea点击:

How to set the color of the place holder text for a UITextField while preserving its existing properties?

iosuitextfield

提问by Ed Fernandez

I have seen some answers that show how to change the placeHolder text color for UITextField by overriding the drawPlaceholderInRect: method such as this one:

我看过一些答案,这些答案显示了如何通过覆盖 drawPlaceholderInRect: 方法来更改 UITextField 的 placeHolder 文本颜色,例如:

iPhone UITextField - Change placeholder text color

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

but that does not maintain the existing attributes such as alignment, font, etc...what is a better way to solve this?

但这并不能保持现有的属性,例如对齐方式、字体等……有什么更好的方法可以解决这个问题?

采纳答案by Ed Fernandez

There is indeed a much better way to handle this now. This will work for iOS 6 and 7.

现在确实有更好的方法来处理这个问题。这适用于 iOS 6 和 7。

(Note this example, I created the code in AwakeFromNib since it won't be changing colors once set. But if you don't use XIB, you will have to change the location where you put this code, such as in drawPlaceholderInRect,)

(注意这个例子,我在 AwakeFromNib 中创建了代码,因为它一旦设置就不会改变颜色。但是如果你不使用 XIB,你将不得不改变你放置这段代码的位置,比如在 drawPlaceholderInRect 中,)

In this example, we create a subclass of UITextField, override awakeFromNib and then set the placeHolder text color to red:

在这个例子中,我们创建了 UITextField 的子类,覆盖了awakeFromNib,然后将 placeHolder 文本颜色设置为红色:

- (void)awakeFromNib
{
    if ([self.attributedPlaceholder length])
    {
        // Extract attributes
        NSDictionary * attributes = (NSMutableDictionary *)[ (NSAttributedString *)self.attributedPlaceholder attributesAtIndex:0 effectiveRange:NULL];

        NSMutableDictionary * newAttributes = [[NSMutableDictionary alloc] initWithDictionary:attributes];

        [newAttributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];

        // Set new text with extracted attributes
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:[self.attributedPlaceholder string] attributes:newAttributes];

    }
}

The nice thing about this approach is that it maintains the current UITextField properties for the placeHolder string and so will allow you to work in IB for most of what you set. In addition, its much more efficient than doing everytime you need to draw. It also allows you to change any other property you want on the placeHolder text while maintaining the rest of the properties.

这种方法的好处是它维护了 placeHolder 字符串的当前 UITextField 属性,因此将允许您在 IB 中为您设置的大部分内容工作。此外,它比每次需要绘制时都要高效得多。它还允许您在保持其余属性的同时更改 placeHolder 文本上所需的任何其他属性。

As mentioned above, if don't use XIBs, then you will need to call this at some other time. If you do put this code in the drawPlaceholderInRect: method, then make sure you call [super drawPlaceholderInRect:] at the end of it.

如上所述,如果不使用 XIB,那么您将需要在其他时间调用它。如果您确实将此代码放在 drawPlaceholderInRect: 方法中,请确保在其末尾调用 [super drawPlaceholderInRect:]。

回答by Forrest

From iOS 6,

从 iOS 6 开始,

Without any subclassing, one can accomplish this with a couple lines of code like so:

在没有任何子类化的情况下,可以使用如下几行代码来完成此操作:

UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];

回答by ABS

There are multiple ways to achieve this.

有多种方法可以实现这一点。

Using Interface Builder or Storyboard

使用 Interface Builder 或 Storyboard

  • Select the Textfield for which you want to change placeholder color
  • go to the Identity inspector menu on Top right of Xcode
  • Add the key value pair this way
  • 选择要更改占位符颜色的文本字段
  • 转到 Xcode 右上角的身份检查器菜单
  • 以这种方式添加键值对

Key path= _placeholderLabel.textColor

关键路径=_placeholderLabel.textColor

Click the Type and chose Color attribute .

单击类型并选择颜色属性。

Then select the color in value.

然后选择颜色值。

enter image description here

enter image description here

Set The placeholder color using code:

使用代码设置占位符颜色

Process 1:

流程一:

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

Process 2 :

过程2:

Override drawPlaceholderInRect:(CGRect)rect method

覆盖 drawPlaceholderInRect:(CGRect)rect 方法

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:14]];
}

回答by Azik Abdullah

The safe way to customize UITextField's placeholder is subclassing the UITextFieldand overriding placeholderRectForBounds:, Apple won't bother you on this one. However, if you want to take the risk, you can try this way:

自定义UITextField占位符的安全方法是继承UITextField和覆盖placeholderRectForBounds:,Apple 不会在这个问题上打扰您。但是,如果您想冒险,可以尝试以下方式:

[self.MyTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];

Source.

来源

回答by Paresh Mangukiya

here See my outputThis is just for get system font name

这里看到我的输出这只是为了获取系统字体名称

for (NSString *familyName in [UIFont familyNames]) {
     for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
         NSLog(@"%@", fontName);

And add a this code in your viewDidLoad

并在您的 viewDidLoad 中添加此代码

_textFieldEmail.attributedPlaceholder =
[[NSAttributedString alloc] initWithString:@"e-mail address"
                                attributes:@{
                                             NSFontAttributeName : [UIFont fontWithName:@"Roboto-LightItalic" size:17.0]
                                             }
 ];

_textFieldPassword.attributedPlaceholder =
[[NSAttributedString alloc] initWithString:@"password"
                                attributes:@{
                                             NSFontAttributeName : [UIFont fontWithName:@"Roboto-LightItalic" size:17.0]
                                             }
 ];