Archive

Archive for September, 2014

SOLVED: Attributed Placeholder UITextField Bug in iOS7

September 16th, 2014

I was creating some custom UI components for an iOS project the other day and I ran into a weird bug. I was subclassing UITextField so I could auto-style all the UITextViews throughout the app (Yes, I know that an iOS purist would tell me to create a UITextField category because overriding UI components is considered “bad,” but I don’t care). I was trying to change the color of the placeholder text in a UITextField using this code:

self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];

This was working fine for a while, then it randomly started throwing compiler errors. Sometimes, it would compile. Other times, it would not. I commented out the code and moved on, but it was bugging me. After Googling around a little, I found a suggestion to add a check for iOS6, since attributed placeholder text only works in iOS7:

if ([self respondsToSelector:@selector(setAttributedPlaceholder:)]) {
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
} else {
    NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
    // TODO: Add fall-back code to set placeholder color.
}

My project target was iOS7 only, so this really shouldn’t have mattered, but it did. After adding the iOS6 check, the compiler errors stopped. I’m sure there is a logical explanation, like I’m allowing an old ARM architecture in my build settings or something.

The really strange part is that the code works perfectly – the placeholder text color gets set correctly every time in my iOS7 app. It just needs the version check for the compiler to play nice.

Top