iOS 7 Translucent Modal View Controller - ios

The App Store app on iOS 7 uses a frosted glass-type effect where it is possible to see the view behind. Is this using an API built into iOS 7 or is it custom code. I was hoping it would be the former but I can't see any obvious references in the documentation. Obvious things like (like setting the alpha property on the modal view) don't seem to have any effect.
To see an example, open the App Store app and press the button at the top-right.

With the release of iOS 8.0, there is no need for getting an image and blurring it anymore. As Andrew Plummer pointed out, you can use UIVisualEffectView with UIBlurEffect.
UIViewController * contributeViewController = [[UIViewController alloc] init];
UIBlurEffect * blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *beView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
beView.frame = self.view.bounds;
contributeViewController.view.frame = self.view.bounds;
contributeViewController.view.backgroundColor = [UIColor clearColor];
[contributeViewController.view insertSubview:beView atIndex:0];
contributeViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:contributeViewController animated:YES completion:nil];
Solution that works before iOS 8
I would like to extend on rckoenes' answer:
As emphasised, you can create this effect by:
Convert the underlying UIView to an UIImage
Blur the UIImage
Set the UIImage as background of your view.
Sounds like a lot of work, but is actually done pretty straight-forward:
1. Create a category of UIView and add the following method:
-(UIImage *)convertViewToImage
{
UIGraphicsBeginImageContext(self.bounds.size);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
2. Make an image of the current view and blur it by using Apple's Image Effect category (download)
UIImage* imageOfUnderlyingView = [self.view convertViewToImage];
imageOfUnderlyingView = [imageOfUnderlyingView applyBlurWithRadius:20
tintColor:[UIColor colorWithWhite:1.0 alpha:0.2]
saturationDeltaFactor:1.3
maskImage:nil];
3. Set it as background of your overlay.
-(void)viewDidLoad
{
self.view.backgroundColor = [UIColor clearColor];
UIImageView* backView = [[UIImageView alloc] initWithFrame:self.view.frame];
backView.image = imageOfUnderlyingView;
backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
[self.view addSubview:backView];
}

Just reimplemented Sebastian Hojas' solution in Swift:
1. Create a UIView extension and add the following method:
extension UIView {
func convertViewToImage() -> UIImage{
UIGraphicsBeginImageContext(self.bounds.size);
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image;
}
}
2. Make an image of the current view and blur it by using Apple's Image Effect (I found a reimplementation of this in Swift here: SwiftUIImageEffects
var imageOfUnderlyingView = self.view.convertViewToImage()
imageOfUnderlyingView = imageOfUnderlyingView.applyBlurWithRadius(2, tintColor: UIColor(white: 0.0, alpha: 0.5), saturationDeltaFactor: 1.0, maskImage: nil)!
3. Set it as background of your overlay.
let backView = UIImageView(frame: self.view.frame)
backView.image = imageOfUnderlyingView
backView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
view.addSubview(backView)

I think this is the easiest solution for a modal view controller that overlays everything with a nice blur (iOS8)
UIViewController * contributeViewController = [[UIViewController alloc] init];
UIBlurEffect * blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *beView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
beView.frame = self.view.bounds;
contributeViewController.view.frame = self.view.bounds;
contributeViewController.view.backgroundColor = [UIColor clearColor];
[contributeViewController.view insertSubview:beView atIndex:0];
contributeViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:contributeViewController animated:YES completion:nil];

There is no API available in the iOS 7 SDK which will allow you to "frost" the underlaying view controller.
What I have done is render the underlaying view to an image, which I then frosted and set that as background the the view that is being presented.
Apple provides a good example for this: https://developer.apple.com/downloads/index.action?name=WWDC%202013
The project you want is called, iOS_RunningWithASnap

A little simplier way to achieve this (based on Andrew Plummer's answer) with Interface Builder (also it removes side effect that appears in Andrews answer):
In IB add Visual Effect View to your View Controller under your other views;
Make top, bottom, left, right constraints from Visual Effect View to top (parent) View, set all of them to 0;
Set Blur Style;
Add the code where you present your new fancy View Controller:
UIViewController *fancyViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"yourStoryboardIDFOrViewController"];
fancyViewController.view.backgroundColor = [UIColor clearColor];
fancyViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:fancyViewController
animated:YES
completion:nil];
Actually, the second and third lines are VERY important - otherwise controller will blink and then turn black.

Since iOS 8, this works:
let vc = UIViewController()
vc.view = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
vc.modalPresentationStyle = .OverFullScreen
let nc = UINavigationController(rootViewController: vc)
nc.modalPresentationStyle = .OverFullScreen
presentViewController(nc, animated: true, completion: nil)
The key is the .OverFullScreen flag and ensuring the viewControllers have a blur UIVisualEffectView that is the first visible view.

As #rckoenes said, there is no Apple provided framework to get that effect. But some people out there already built good alternatives, like this one for example:
https://github.com/JagCesar/iOS-blur/

A couple of alternative approaches that also work on iOS 5 and 6:
FXBlurView: https://github.com/nicklockwood/FXBlurView
iOS RealtimeBlur: https://github.com/alexdrone/ios-realtimeblur

Fast & easy solution
with XIB support you can use for the old school boys
https://github.com/cezarywojcik/CWPopup

Instead of presenting the viewController as a modalView, you could add it as a child viewController and create a custom animation. You would then only need to change the default view of the viewController to a UIToolBar in viewDidLoad.
This will allow you to mimic the appstore's blurred modal view as closely as possible.

I have uploaded my take of the blurred view controller to [GitHub][1]. It also comes with a segue subclass so you can use it in your storyboards.
Repository: https://github.com/datinc/DATBlurSegue

Apple released the UIImageEffect category for those effects. Those category should be added manually to the project, and it support iOS7.

You can use UIToolbar as background.
By default UIToolbar have 50px height.
Add auto layout constraints on UIToolbar.
Then select height constraint and modify it.
Hierarchy will look like this:
UIView -> clear colour for background.
- UIToolbar
- Other contents.

Related

Blur Effect in iOS8

I am trying to create blur effect on the UIView as well as I want to add vibrancy Effect so that I can highlight my buttons and use them. I am trying to learn via apple docs and couple of tutorials but unable to get in the following steps I am doing are correct.
Steps 1. I am creating a blur view adding it as subview to present view so that it looks blur.
Step 2 . Then i am creating a vibrancy view for the blur effect and adding it to contentview of blurview.
But i am unable to get the blur effect, can anyone help me to understand
1. If the following steps are correct.
2. If not how should ideally the sequence be.
3. How to highlight those buttons and use them. ( I am attaching the snaphot of my storyboard too).
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIBlurEffect *blurEffect= [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
[blurView setUserInteractionEnabled:false];
[self.view addSubview:blurView];
UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
UIVisualEffectView *vibrancyView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
[vibrancyView setTranslatesAutoresizingMaskIntoConstraints:NO];
//[vibrancyView.contentView addSubview:s];
[blurView.contentView addSubview:vibrancyView];
}
The chief problem with your code is that you have neglected to give your blur view any size. Therefore it has zero size. Thus you will not see it do anything; it is, in effect, invisible. The most it can blur would be a single pixel behind it, and you are unlikely to notice that.
You are not setting the frame for your blurView and vibrancyView.
blurView.frame = self.view.frame;
vibrancyView.frame = self.view.frame;

iOS 8 UIVisualEffect View with UIBlurEffect becomes opaque

I am trying to present a view with a blurred transparent background over an existing view. I am able to get the desired effect during the presentation animation, but once the blurred view is fully presented, it becomes opaque.
Here's how I am presenting it:
if (!UIAccessibilityIsReduceTransparencyEnabled()) {
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
blurEffectView.frame = self.view.bounds;
[blurEffectView setOpaque:NO];
[self.view insertSubview:blurEffectView atIndex:0];
[blurEffectView setTranslatesAutoresizingMaskIntoConstraints:false];
}
In my blurred view, I have set the background color to clear color and opaque to NO. Any thoughts?
Note that any UIVisualEffectView with a UIBlurEffect will be opaque if the "Reduce Transparency" accessibility setting is on.
(Settings > General > Accessibility > Increase Contrast > Reduce Transparency)
(Which is what your are actually checking with your if (!UIAccessibilityIsReduceTransparencyEnabled()) statement.)
I wound up writing a custom presentation controller. Never found a way to do this with standard presentations.
In the view where I want the effect viewDidLoad:
//Custom Modal Presentation
[self setModalPresentationStyle:UIModalPresentationCustom];
//blur the controlContainerView
if (!UIAccessibilityIsReduceTransparencyEnabled()) {
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:[self blurStyle]];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
blurEffectView.frame = self.controlContainerView.bounds;
[blurEffectView setOpaque:NO];
[self.controlContainerView insertSubview:blurEffectView atIndex:0];
[blurEffectView setTranslatesAutoresizingMaskIntoConstraints:false];
}
Invoking the above view:
//in .h
#property (nonatomic) id<UIViewControllerTransitioningDelegate> transitioningDelegate;
//In .m
BlurViewController *blurVC = [self.storyboard instantiateViewControllerWithIdentifier:#"blurView"];
_transitioningDelegate = [[MyCustomOverlayDelegate alloc] init];
[blurView setModalPresentationStyle:UIModalPresentationCustom];
[blurView setTransitioningDelegate:[self transitioningDelegate]];
[blurView setBlurStyle:UIBlurEffectStyleLight];
[self presentViewController: blurView animated:YES completion:nil];
You will also need to import the entire stack of presentation controller classes. For me, these were OverlayDelegate, OverlayTransitionAnimator, and OverlayPresentationController. This is where the real work is.
If you can, check out WWDC 2014 session 228 "A look inside presentation controllers". Custom presentations are covered about half-way through. It was what I used to base my custom stack on and reasonably straight forward.
From the documentation:
A UIBlurEffect object applies a blurring effect to the content layered behind a UIVisualEffectView.
So I think the problem is your clear backgroundColor. If you have some kind of content or coloring behind your UIVisualEffectView, it should work.
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
UIVisualEffectView *blurredView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
This simple code snippet does work for me. In the ViewController I want to show the blurred effect I just call [[self view] addSubView:blurredView]
Simply set the view controller which holds the blurred view like this:
myViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
It prevents optimisation which removes views from the view hierarchy which in turn makes the blurred view presented first and thus making it opaque.

Strange blur artefacts with UIVisualEffectView

I have a UIVisualEffectView which is causing some strange artefacts right when it appears. The UIVisualEffectView is added in code after the view loads because it's not available in iOS 7.
Look at the blurred text background over the street view image: http://s.swic.name/Z3UL
The blur takes a good 0.1 seconds to appear, and before that it's just a lower resolution background shining through like the blur hasn't been calculated yet.
Any idea what is going on? I'm adding the blur in awakeFromNib using this code
- (void)addBlurWithColor:(UIColor *)color andStyle:(UIBlurEffectStyle)style andVibrancy:(BOOL)vibrancy
{
if (UIDevice.supportsVisualEffects && NSClassFromString(#"UIVisualEffectView") && !UIAccessibilityIsReduceTransparencyEnabled()) {
self.backgroundColor = color;
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:style];
UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = self.bounds;
visualEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
NSArray *subviews = self.subviews;
[self addSubview:visualEffectView];
[self sendSubviewToBack:visualEffectView];
if (vibrancy) {
UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
[vibrancyEffectView setFrame:self.bounds];
vibrancyEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
for (UIView *subview in subviews) {
[vibrancyEffectView.contentView addSubview:subview];
}
[[visualEffectView contentView] addSubview:vibrancyEffectView];
}
}
}
Edit: The video just has slow animations enabled, the transition is a regular push segue.
Edit2: I get the same strange behaviour if i just drag drop a "UIVisualEffectView with Blur" in Interface Builder, so the code above shouldn't be to blame.
Found the problem, when the view appears I'm reloading the tableview inside [UIView transitionWithView:...] which alters the alpha which apparently is a big no-no when it comes to UIVisualEffectViews!
According to UIVisualEffectView Documentation;
When using the UIVisualEffectView class, avoid alpha values that are
less than 1. Creating views that are partially transparent causes the
system to combine the view and all the associated subviews during an
offscreen render pass. UIVisualEffectView objects need to be combined
as part of the content they are layered on top of in order to look
correct. Setting the alpha to less than 1 on the visual effect view or
any of its superviews causes many effects to look incorrect or not
show up at all.
https://developer.apple.com/library/ios/documentation/uikit/reference/UIVisualEffectView/index.html

How do I make the area on the top of a UISearchBar (when on a UITableView) in iOS 7 transparent?

Here is a picture describing the problem. Notice that the area above the UISearchBar does not have the background as below it. I don't want the gray color, I want the dark maroon background when pulling down on the UITableView.
Everything I know of is set to [UIColor clearColor], including backgrounds of views, etc. It works fine in iOS 6 but not iOS 7!
I've also attached a sample project so someone can take a look and see what I am doing wrong here?
Click here to download my sample project
Maybe I am just missing something stupid?
Thanks!
Two things you could do: 1) add an explicit clear background view to the UITableView. Or, 2) set your UIImageView to be the background view of the UITableView.
Either of these work. Here's the code that makes your sample work:
- (void)viewDidLoad
{
[super viewDidLoad];
UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
backgroundImageView.image = [UIImage imageNamed:#"Film_bg.png"];
[self.view addSubview:backgroundImageView];
[self.view sendSubviewToBack:backgroundImageView];
// solution 1
// self.tableView.backgroundView = [UIView new];
// self.tableView.backgroundView.backgroundColor = [UIColor clearColor];
// solution 2
self.tableView.backgroundView = backgroundImageView;
}

Achieving bright, vivid colors for an iOS 7 translucent UINavigationBar

iOS 7.1 UPDATE: Looks like the workaround for modifying the alpha channel in the UINavigationBar has been ignored in this update. Right now, the best solution seems to be to just 'deal with it' and hope that whatever color you choose can render a translucent effect. I am still looking into ways of getting around this.
iOS 7.0.3 UPDATE: The GitHub library we created has been updated to slightly work around this issue when using iOS 7.0.3. Unfortunately, there is no magic formula to support both colors created in iOS 7.0.2 and earlier and iOS 7.0.3. Seems like Apple improved the saturation, but at the cost of opacity (since the blurred translucency is dependant on the opacity level). I, along with a few others, are working on creating a much better fix for this.
I'm sure many people have already come across the problem where iOS 7 tends to desaturate the color of a UINavigationBar that is translucent.
My goal is to achieve a UINavigationBar with this tint color, but translucent:
However, with translucency, I'm getting this. The background view is white, which I understand will make this view a bit lighter:
Is there any way to achieve the original color while still having translucency? I've noticed Facebook has been able to get their bar to be their rich, blue color, as displayed here:
..so I know there has to be some way. Background views obviously make a difference here, but most of their content is also gray/white. It seems that regardless of whatever bar tint color you put in, you are unable to get vivid colors under translucency.
Updated with solution.
Here's the solution that I ended up coming up with. I took aprato's solution and then encompassed the custom UINavigationBar within a UINavigationController subclass. I have created a repository that has this implementation listed below, along with an example app.
////////////////////////////
// CRNavigationBar.m
////////////////////////////
#import "CRNavigationBar.h"
#interface CRNavigationBar ()
#property (nonatomic, strong) CALayer *colorLayer;
#end
#implementation CRNavigationBar
static CGFloat const kDefaultColorLayerOpacity = 0.5f;
static CGFloat const kSpaceToCoverStatusBars = 20.0f;
- (void)setBarTintColor:(UIColor *)barTintColor {
[super setBarTintColor:barTintColor];
if (self.colorLayer == nil) {
self.colorLayer = [CALayer layer];
self.colorLayer.opacity = kDefaultColorLayerOpacity;
[self.layer addSublayer:self.colorLayer];
}
self.colorLayer.backgroundColor = barTintColor.CGColor;
}
- (void)layoutSubviews {
[super layoutSubviews];
if (self.colorLayer != nil) {
self.colorLayer.frame = CGRectMake(0, 0 - kSpaceToCoverStatusBars, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + kSpaceToCoverStatusBars);
[self.layer insertSublayer:self.colorLayer atIndex:1];
}
}
#end
////////////////////////////
// CRNavigationController.m
////////////////////////////
#import "CRNavigationController.h"
#import "CRNavigationBar.h"
#interface CRNavigationController ()
#end
#implementation CRNavigationController
- (id)init {
self = [super initWithNavigationBarClass:[CRNavigationBar class] toolbarClass:nil];
if(self) {
// Custom initialization here, if needed.
}
return self;
}
- (id)initWithRootViewController:(UIViewController *)rootViewController {
self = [super initWithNavigationBarClass:[CRNavigationBar class] toolbarClass:nil];
if(self) {
self.viewControllers = #[rootViewController];
}
return self;
}
#end
iOS 7.0.3 UPDATE: As you see above 7.0.3 changed things. I've updated my gist. Hopefully this will just go away as people upgrade.
Original Answer:
I ended up with a hack combining the two of the other answers. I'm subclassing UINavigationBar and adding a layer to the back with some extra space to cover if any of the various height status bars are up. The layer gets adjusted in layout subviews and the color changes whenever you set barTintColor.
Gist: https://gist.github.com/aprato/6631390
setBarTintColor
[super setBarTintColor:barTintColor];
if (self.extraColorLayer == nil) {
self.extraColorLayer = [CALayer layer];
self.extraColorLayer.opacity = self.extraColorLayerOpacity;
[self.layer addSublayer:self.extraColorLayer];
}
self.extraColorLayer.backgroundColor = barTintColor.CGColor;
layoutSubviews
[super layoutSubviews];
if (self.extraColorLayer != nil) {
[self.extraColorLayer removeFromSuperlayer];
self.extraColorLayer.opacity = self.extraColorLayerOpacity;
[self.layer insertSublayer:self.extraColorLayer atIndex:1];
CGFloat spaceAboveBar = self.frame.origin.y;
self.extraColorLayer.frame = CGRectMake(0, 0 - spaceAboveBar, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + spaceAboveBar);
}
The behavior of tintColor for bars has changed on iOS 7.0. It no longer affects the bar's background and behaves as described for the tintColor property added to UIView. To tint the bar's background, please use -barTintColor.You can use following code to make the app work with both ios6 and ios7.
if(IS_IOS7)
{
self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
self.navigationController.navigationBar.translucent = NO;
}
else
{
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}
IS_IOS7 is a macro which is defined in pch file as follows.
#define IS_IOS7 ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0)
I didn't come up with this solution but it seems to work fairly well. I just added it to viewDidLoad on my subclass of UINavigationController.
Source: https://gist.github.com/alanzeino/6619253
// cheers to #stroughtonsmith for helping out with this one
UIColor *barColour = [UIColor colorWithRed:0.13f green:0.14f blue:0.15f alpha:1.00f];
UIView *colourView = [[UIView alloc] initWithFrame:CGRectMake(0.f, -20.f, 320.f, 64.f)];
colourView.opaque = NO;
colourView.alpha = .7f;
colourView.backgroundColor = barColour;
self.navigationBar.barTintColor = barColour;
[self.navigationBar.layer insertSublayer:colourView.layer atIndex:1];
One low-fi way would probably be pinning a UIView that is the height of the Navigation Bar to the top of the view behind the bar. Make that view the same color as the navigation bar but play with the alpha until you get the desired effects:
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.navigationController.navigationBar.frame), 64)];
backgroundView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:1 alpha:.5];
[self.navigationController.view insertSubview:backgroundView belowSubview:self.navigationController.navigationBar];
UIView behind
(Changed color from lower examples to emphasis transparency. Transparency/blurring is more noticeable when in movement.)
Subclassing the UINavigationBar and placing that same view above the background but behind everything else will probably achieve similar results while being less hacky.
Another solution I've seen tossed around is playing with the alpha of the UINavigationBar:
self.navigationController.navigationBar.alpha = 0.5f;
Edit: Actually, after testing it seems like this doesn't provide the intend behavior (or any behavior):
.8 alpha
Unadjusted alpha
Obviously, you will only want to do this on iOS 7 devices. So, add some version check before you implement any of these.
Instead of creating your UIColor object in the RGB format, use HSB and increase the saturation parameter. (Credits to Sam Soffes who describes this method here)
navigationBar.barTintColor = [UIColor colorWithHue:0.555f saturation:1.f brightness:0.855f alpha:1.f];
Note: This solution is a tradeoff and doesn't work well for colors with high saturation.
To pick the HSB color from your design you can use a tool like ColorSnapper which allows you to simply copy the UIColor HSB format.
You can also try the UIColor Category (GitHub Link) from David Keegan to modify existing colors.
The problem has now been fixed by Apple in the new 7.0.3 release.
I used #aprato's solution but found a few corner cases where the new layers from new VCs (eg. UINavigationItemButtonViews, UINavigationItemViews, etc) would be automatically inserted into a position below the extraColorLayer (which would cause those title or button elements to be affected by the extraColorLayer and thus fainter in color than they normally would be). So I adjusted #aprato's solution to force the extraColorLayer to stay at the index position 1. At index position 1, the extraColorLayer stays right above the _UINavigationBarBackground, but underneath everything else.
Here's my class implementation:
- (void)setBarTintColor:(UIColor *)barTintColor
{
[super setBarTintColor:barTintColor];
if (self.extraColorLayer == nil)
{
self.extraColorLayer = [CALayer layer];
self.extraColorLayer.opacity = kDefaultColorLayerOpacity;
[self.layer insertSublayer:self.extraColorLayer atIndex:1]; // This way the text comes out clear
}
self.extraColorLayer.backgroundColor = barTintColor.CGColor;
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (self.extraColorLayer != nil)
{
self.extraColorLayer.frame = CGRectMake(0, 0 - kSpaceToCoverStatusBars, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + kSpaceToCoverStatusBars);
}
}
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview
{
[super insertSubview:view aboveSubview:siblingSubview];
[self.extraColorLayer removeFromSuperlayer];
[self.layer insertSublayer:self.extraColorLayer atIndex:1]; // This way the text comes out clear
}
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index
{
[super insertSubview:view atIndex:index];
[self.extraColorLayer removeFromSuperlayer];
[self.layer insertSublayer:self.extraColorLayer atIndex:1]; // This way the text comes out clear
}
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview
{
[super insertSubview:view belowSubview:siblingSubview];
[self.extraColorLayer removeFromSuperlayer];
[self.layer insertSublayer:self.extraColorLayer atIndex:1]; // This way the text comes out clear
}
I've improved your code in my fork: https://github.com/allenhsu/CRNavigationController
With my modification, the result color on screen (picked on white background) will be exactly the same value passed into setBarTintColor. I think it's an amazing solution.
None of these hacks are required :). Simply set:
self.navigationController.navigationBar.translucent = NO;
For iOS 7, the default translucency has been kept to TRUE.
On a related note, you can set your title text color (with shadow) easily via:
NSShadow *titleShadow = [[NSShadow alloc] init];
titleShadow.shadowOffset = CGSizeMake(0.0f, -1.0f);
titleShadow.shadowColor = [UIColor blackColor];
NSDictionary *navbarTitleTextAttributes = #{NSForegroundColorAttributeName: [UIColor whiteColor],
NSShadowAttributeName: titleShadow};
[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
I came across this Q/A while trying to setup an uniformly colored navigation bar with transparency DISABLED on iOS 7.
After experimenting a while with barTintColor I figured out that a very easy way of having an opaque navigation bar is to make a single pixel image of the desired color, make a stretchable image out of it, and setting it to the backgroundImage of the navigation bar.
UIImage *singlePixelImage = [UIImage imageNamed:#"singlePixel.png"];
UIImage *resizableImage = [singlePixelImage resizableImageWithCapInsets:UIEdgeInsetsZero];
[navigationBar setBackgroundImage:resizableImage forBarMetrics:UIBarMetricsDefault];
Three lines of code, very simple and works BOTH on iOS 6 and iOS 7 (barTintColor is unsupported on iOS 6).
Theres a great Dropin UINavigationController replacement available from Simon Booth available at GitHub Here GitHub - C360NavigationBar
If you're backward supporting iOS6 do a check on the root view controller as such:
PatientListTableViewController *frontViewController = [[PatientListTableViewController alloc] init];
UINavigationController *navViewController = [[UINavigationController alloc] initWithNavigationBarClass:[C360NavigationBar class] toolbarClass:nil];
if ([navViewController.view respondsToSelector:#selector(setTintColor:)]) {
//iOS7
[navViewController.view setTintColor:self.navBarTintColor];
[[C360NavigationBar appearance] setItemTintColor:self.navBarItemTintColor];
} else {
//iOS6
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
navViewController.navigationBar.tintColor = self.navBarTintColor;
}
[navViewController pushViewController:frontViewController animated:NO];
self.window.rootViewController = navViewController;
As #bernhard mentioned above it's possible to saturate the bar tint color to get desired navigation bar appearance.
I wrote an BarTintColorOptimizer utility for that kind of adjustment. It optimizes translucent bar tint color to make the bar's actual color match the desired color in iOS 7.x and later. Look at this answer for details.
Frankly speaking, above answers might be right but following trick worked for me with very ease.
// this is complete 100% transparent image
self.imageBlack = [[UIImage imageNamed:#"0102_BlackNavBG"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 2, 0, 2)
resizingMode:UIImageResizingModeStretch];
// this is non-transparent but iOS7
// will by default make it transparent (if translucent is set to YES)
self.imageRed = [[UIImage imageNamed:#"0102_RedNavBG"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 2, 0, 2)
resizingMode:UIImageResizingModeStretch];
// some navigation controller
[nvCtrLeft.navigationBar setBackgroundImage:self.imageRed
forBarMetrics:UIBarMetricsDefault];
// some another navigation controller
[nvCtrCenter.navigationBar setBackgroundImage:self.imageRed
forBarMetrics:UIBarMetricsDefault];
Here are the images used for self.imageRed and self.imageBlack.
< > black image is in this brackets won't be visible as it is transparent :)
< > red image is in this brackets.
is there a way to use #aprato solution without subclassing UINavigationBar.
In my project my main view is a UIViewController.
the problem is that the navigationController is a readonly property, is there a way to use you class with my project because i can't use : [[UINavigationController alloc] initWithNavigationBarClass:
thanks
An easy way to get the color you want is using
[<NAVIGATION_BAR> setBackgroundImage:<UIIMAGE> forBarPosition:<UIBARPOSITION> barMetrics:<UIBARMETRICS>];
As long as your image has some alpha, the translucency will work and you can set the alpha by changing the image. This was just added in iOS7. The width and height for the image are 640x88px for vertical (add 20 to the 88 if you want it to be underneath the status bar).

Resources