不说话,上码:
#import "UINavigationBar+Styled.h" #import <objc/runtime.h> @implementation UINavigationBar (Styled) - (void)layoutSubviewsWithShadows { // Since we exchanged implementations, this actually calls UIKit's layoutSubviews [self layoutSubviewsWithShadows]; // Super sneaky/hacky way of getting dropshadows on all our styled navbars. //if ([[self class] respondsToSelector:@selector(appearance)]) { NSInteger shadowTag = 1; UIView *shadowView = [self viewWithTag:shadowTag]; if (shadowView == nil) { UIImageView *shadowImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navbar_shadow"]]; shadowImg.frame = CGRectMake(0.0f, self.frame.size.height, self.frame.size.width, 15.0f); shadowImg.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth; shadowImg.tag = shadowTag; [self addSubview:shadowImg]; [shadowImg release]; } //} } + (void)load { Method origMethod = class_getInstanceMethod(self, @selector(layoutSubviews)); Method newMethod = class_getInstanceMethod(self, @selector(layoutSubviewsWithShadows)); method_exchangeImplementations(origMethod, newMethod); } @end
上面代码是wordpress源码中的一个 category,目的是给ios5.0 之上的版本加阴影图片。但是ios5.0 的
appearance 不提供这个接口,所以就有了上面的代码的出现。
关键点:
一、+ (void)load 方法
官方文档说明
Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading。
意思就是运行时加载这个class或者category的时候会调用这个消息,来设定一个时机做一些class层面上自定义的事情。上述代码就是利用这个时机交换了系统的一个api消息,来实现定制。
这个方法只会调用一次。
二、自定义系统方法
例如上述代码,layoutSubviewsWithShadows 交换了系统的 layoutSubviews,但是需要注意的是,在你想发送系统消息的时候,还是要写成 [self layoutSubviewsWithShadows];
代码中有特意的注释,这部分代码,会在每次需要layoutSubViews的时候调用。
wordpress是个宝藏, 里面有很多值得学习的地方,待我慢慢挖掘。