Make all instances of UINavigationBar titles lower

2019-09-09 04:54发布

问题:

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.