如何在保留现有属性的同时为UITextField设置占位符文本的颜色? [英] How to set the color of the place holder text for a UITextField while preserving its existing properties?

查看:130
本文介绍了如何在保留现有属性的同时为UITextField设置占位符文本的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一些答案,显示如何通过覆盖drawPlaceholderInRect:方法来更改UITextField的placeHolder文本颜色,如下所示:

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:

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

但是它不维护对齐,字体等现有属性...什么是解决此问题的更好方法?

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

推荐答案

现在确实有一种更好的方法可以解决这个问题。这适用于iOS 6和7。

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

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

(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,)

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

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

- (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];

    }
}

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

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.

如上所述,如果不使用XIB,那么你需要在其他时间打电话给这个。如果你把这段代码放在drawPlaceholderInRect:方法中,那么请确保你在它的末尾调用[super drawPlaceholderInRect:]。

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.

这篇关于如何在保留现有属性的同时为UITextField设置占位符文本的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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