简体   繁体   中英

How to add UIVisualEffectView to UINavigationBar in iOS 8?

I want to use UIVIsualEffectView to add blurry effect to Navigation Bar. I have custom navigation bar class as following.

Header file

#import <UIKit/UIKit.h>

@interface GSNavigationBar : UINavigationBar
@end

And immplementation file looks like following

#import "GSNavigationBar.h"

@implementation GSNavigationBar

- (void) awakeFromNib {

     UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
     visualEffectView.frame = CGRectMake(0, -21, self.frame.size.width , self.frame.size.height + 21);
     [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
     [self insertSubview:visualEffectView atIndex:1000];
}
@end

With the code above I am able to implement blurry effect to Navigation Bar. Upon pushing a view controller (by using 'Push' segue), left bar button items and right bar items in the navigation bar become inactive. For more clarity I have attached screenshots of the view controllers.


This is view controller #1. All navigation item buttons are clickable
This is view controller #2. We land up here due to push segue from view controller #1. Navigation item buttons are NOT clickable. Also the title goes missing. I had set the title using self.title

NavigationBar with translucent = YES already has a blur effect.

So just use it.

This is to make navigation bar fully transparent, if you have blurred background I believe it will be effect that you needed.

Swift:

func setupNavigationBar() {
    navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
    navigationController!.navigationBar.shadowImage = UIImage()
    navigationController!.navigationBar.translucent = true
}

Objective C:

- (void) setupNavigationBar{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];

    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
}
[self sendSubviewToBack:visualEffectView];

set the property UserInteractionEnabled to NO (false in swift) on the UIVisualEffect.

so on your code you should add:

visualEffectView.userInteractionEnabled = NO

this should make your navigationItems left and right usable

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