Label Alignment in iOS 6 - UITextAlignment deprecated
The labelAlignment
property change is probably related to Apple’s introducing NSAttributedStrings to more of the iOS controls, and therefore needing to change the UIText… properties to NSText… properties.
So if you’ve upgraded to iOS6, you’re in clover; just switch from UITextAlignmentCenter
to NSTextAlignmentCenter
and enjoy the fancy new strings.
But if you’re working with a complex project and would prefer that the earth not move so much under your feet, you might want to stick with an older version for a while, and adapt your code for multiple versions, something like this:
// This won't compile:
if ([label respondsToSelector:@selector(attributedText:)])
label.textAlignment = UITextAlignmentCenter;
else
label.textAlignment = NSTextAlignmentCenter;
The above approach works for new methods; you get warnings but everything runs fine. But when the compiler sees a constant that it doesn’t know about, it turns red and stops in its tracks. There’s no way to sneak NSTextAlignmentCenter
past it. (Well, there might be a way to customize the compiler’s behavior here, but it seems inadvisable.)
The workaround is to add some conditional preprocessor defines. If you put something like this in your class’s h file (or perhaps in an imported constants file -- which must itself include #import <UIKit/UIKit.h>
in order to ever know about the NSText... constants)…
#ifdef NSTextAlignmentCenter // iOS6 and later
# define kLabelAlignmentCenter NSTextAlignmentCenter
# define kLabelAlignmentLeft NSTextAlignmentLeft
# define kLabelAlignmentRight NSTextAlignmentRight
# define kLabelTruncationTail NSLineBreakByTruncatingTail
# define kLabelTruncationMiddle NSLineBreakByTruncatingMiddle
#else // older versions
# define kLabelAlignmentCenter UITextAlignmentCenter
# define kLabelAlignmentLeft UITextAlignmentLeft
# define kLabelAlignmentRight UITextAlignmentRight
# define kLabelTruncationTail UILineBreakModeTailTruncation
# define kLabelTruncationMiddle UILineBreakModeMiddleTruncation
#endif
…you can do this:
label.textAlignment = kLabelAlignmentCenter;
And this:
label.lineBreakMode = kLabelTruncationMiddle;
Etc.
Since these UIText/NSText changes are likely to be popping up for multiple controls, this approach is quite handy.
(Caveat: Being a member of the aforementioned steady-earth lovers, I have tested this with an old version, but not yet with iOS6.)
In iOS6 you can use
label.textAlignment = NSTextAlignmentCenter;