iOS7 自定义statusBar的颜色

//
//  UINavigationBar+statusBarColor.h
//  JASidePanels
//
//  Created by simon.zeng on 6/5/14.
//
//

#import <UIKit/UIKit.h>

@interface UINavigationBar (statusBarColor)

@property (nonatomic, strong, setter = setStatusBarColor:, getter=statusBarColor) UIColor * statusBarColor;

@end
//
//  UINavigationBar+statusBarColor.m
//  JASidePanels
//
//  Created by simon.zeng on 6/5/14.
//
//

#import "UINavigationBar+statusBarColor.h"

#import <objc/runtime.h>

@implementation UINavigationBar (statusBarColor)

+ (void)load
{
    method_exchangeImplementations(class_getInstanceMethod(self, @selector(layoutSubviews)), class_getInstanceMethod(self, @selector(__layoutSubviews)));
}

- (void)__layoutSubviews
{
    [self __layoutSubviews];
    
    if (self.statusBarColor)
    {
        Class backgroundClass = NSClassFromString(@"_UINavigationBarBackground");
        Class statusBarBackgroundClass = NSClassFromString(@"_UIBarBackgroundTopCurtainView");
        
        for (UIView * aSubview in self.subviews)
        {
            if ([aSubview isKindOfClass:backgroundClass]) {
                BOOL hasStatusBarBackgroundView = NO;
                
                for (UIView * aaSubview in aSubview.subviews)
                {
                    if ([aaSubview isKindOfClass:statusBarBackgroundClass]) {
                        aaSubview.backgroundColor = self.statusBarColor;
                        hasStatusBarBackgroundView = YES;
                    }
                }
                
                if (!hasStatusBarBackgroundView)
                {
                    UIView * statusBarBackgroundView = [[statusBarBackgroundClass alloc] initWithFrame:CGRectMake(0, -20, aSubview.bounds.size.width, 20.0)];
                    statusBarBackgroundView.backgroundColor = self.statusBarColor;
                    
                    [aSubview addSubview:statusBarBackgroundView];
                }
            }
        }
    }
}


- (void)setStatusBarColor:(UIColor *)color
{
    objc_setAssociatedObject(self, @selector(statusBarColor), color, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    [self setNeedsLayout];
}

- (UIColor *)statusBarColor
{
    return objc_getAssociatedObject(self, @selector(statusBarColor));
}

@end


你可能感兴趣的:(iOS7 自定义statusBar的颜色)