#import "objc/runtime.h" void Swizzle(Class c, SEL orig, SEL new) { Method origMethod = class_getInstanceMethod(c, orig); Method newMethod = class_getInstanceMethod(c, new); if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))){ class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); } else { method_exchangeImplementations(origMethod, newMethod); } }
运用场景,运用实例
int main(int argc, char *argv[]) { @autoreleasepool { Swizzle([UINavigationBar class], @selector(drawRect:), @selector(SP_drawRect:)); Swizzle([UITabBar class], @selector(drawRect:), @selector(SP_drawRect:)); return UIApplicationMain(argc, argv, nil, NSStringFromClass([SNAppDelegate class])); } }
分类里重写些方法
@interface UINavigationBar (SPExtension) - (void)SP_drawRect:(CGRect)rect; @end
实现
@implementation UINavigationBar (SPExtension) + (Class)class { return NSClassFromString(@"SPNavigationBar"); } - (void)SP_drawRect:(CGRect)rect { if (self.tag == SPCommonNavigationBar) { if ([self viewWithTag:kSPNaviBarShadowTag] == nil) { CGRect rf = CGRectMake(0, 0, 320, 44); [[UIImage imageNamed:@"title_bar_background.png"] drawInRect:rf]; // [[UIImage imageNamed:@""] drawInRect:rf];//sp_navigation_bar_bg // self.backgroundColor = [UIColor clearColor]; // UIView *shadowLayer = [[UIView alloc] initWithFrame:CGRectMake(0, rect.size.height - 0, rect.size.width, 0)]; // shadowLayer.alpha = 1.0; // shadowLayer.tag = kSPNaviBarShadowTag; // // CAGradientLayer *grad2 = [CAGradientLayer layer]; // grad2.frame = CGRectMake(0, 0, rect.size.width, 3); // grad2.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithHue:0 saturation:0 brightness:0 alpha:.0] CGColor], (id)[[UIColor colorWithHue:0 saturation:0 brightness:0 alpha:.5] CGColor], nil]; // // [shadowLayer.layer insertSublayer:grad2 atIndex:0]; // [self insertSubview:shadowLayer atIndex:10]; // [shadowLayer release]; } else { UIView *shadowLayer = [self viewWithTag:kSPNaviBarShadowTag]; shadowLayer.alpha = 1.0; shadowLayer.frame = CGRectMake(0, rect.size.height - 3, rect.size.width, 3); CALayer *grad2 = [shadowLayer.layer.sublayers objectAtIndex:0]; grad2.frame = CGRectMake(0, 0, rect.size.width, 3); } } else { UIView *shadowLayer = [self viewWithTag:kSPNaviBarShadowTag]; if (shadowLayer) { shadowLayer.alpha = 0.0; } [self SP_drawRect:rect]; } } @end
好像就处理了一下背景还是什么的,然而并不怎么高级的感觉