问题
Some titles in this iOS app are defined in the storyboard. Some of the titles are being set programmatically. Is there a simple way (Obj-C categories maybe?) to make all the titles lowercase without subclassing?
回答1:
It is possible with a bit of objective-c magic, using method_exchangeImplementations (AKA "Method Swizzling")
#import <objc/runtime.h>
@interface UINavigationItem (New)
@end
@implementation UINavigationItem (New)
- (void)setTitleLower:(NSString *)title {
[self setTitleLower:[title lowercaseString]];
}
+ (void)load {
method_exchangeImplementations(class_getInstanceMethod(self, @selector(setTitle:)), class_getInstanceMethod(self, @selector(setTitleLower:)));
}
@end
Now each call to someNavItem.title = @"Whatever" ([UINavigationItem setTitle:(NSString*)title]) should go through setTitleLower, which in turn also calls the original setTitle with a minor modification, lowercasing the title.
I would avoid having to implement such a category just for the sake of lower-casing all titles for each UINavigationItem. I guess you're experimenting categories.
来源:https://stackoverflow.com/questions/17625221/make-all-instances-of-uinavigationbar-titles-lowercase-without-subclassing