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

前端 未结 5 952
没有蜡笔的小新
没有蜡笔的小新 2021-02-18 18:37

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 UITe

5条回答
  •  一整个雨季
    2021-02-18 19:08

    There is indeed a much better way to handle this now. This will work for iOS 6 and 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,)

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

    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.

    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.

提交回复
热议问题