简体   繁体   中英

Different UINavigationBar BarTint Color when presented Modally

Right now I am globally changing the bartint color in the AppDelegate like this.

[[UINavigationBar appearance] setBarTintColor:[UIColor greenColor]];

Is there a way to keep this, but globally alter the BarTintColor when those views are presented modally?

So I decided to create a category that swizzled viewWillAppear to solve this.

@implementation UIViewController (IsModal)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];

        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(extended_viewWillAppear:);

        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        BOOL didAddMethod =
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));

        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

- (void)extended_viewWillAppear:(BOOL)animated {
    [self extended_viewWillAppear:animated];
    [self styleIfModal];
}

- (void)styleIfModal {
    if([self isModal] && self.navigationController != nil) {
        [self.navigationController.navigationBar setBarTintColor:[UIColor grayColor]];
    }
}

- (BOOL)isModal
{
    return self.presentingViewController.presentedViewController == self || (self.navigationController != nil && self.navigationController.presentingViewController.presentedViewController == self.navigationController) || [self.tabBarController.presentingViewController isKindOfClass:[UITabBarController class]];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM