Make UINavigationBar transparent

2019-01-02 21:46发布

How do you make a UINavigationBar transparent? Though I want its bar items to remain visible.

16条回答
放荡不羁爱自由
2楼-- · 2019-01-02 22:06

After doing what everyone else said above, i.e.:

navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true

... my navigation bar was still white. So I added this line:

navigationController?.navigationBar.backgroundColor = .clear

... et voila! That seemed to do the trick.

查看更多
Ridiculous、
3楼-- · 2019-01-02 22:07

For anyone who wants to do this in Swift 2.x:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = true

or Swift 3.x:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
查看更多
贪生不怕死
4楼-- · 2019-01-02 22:08

C# / Xamarin Solution

NavigationController.NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default);
NavigationController.NavigationBar.ShadowImage = new UIImage();
NavigationController.NavigationBar.Translucent = true;
查看更多
时光不老,我们不散
5楼-- · 2019-01-02 22:12

This works for Swift 2.0.

navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController!.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.translucent = true
查看更多
狗以群分
6楼-- · 2019-01-02 22:12

If anybody is wondering how to achieve this in iOS 7+, here's a solution (iOS 6 compatible too)

In Objective-C

[self.navigationBar setBackgroundImage:[UIImage new]
                         forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;

In swift 3 (iOS 10)

self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true

In swift 2

self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.translucent = true

Discussion

Setting translucent to YES on the navigation bar does the trick, due to a behavior discussed in the UINavigationBar documentation. I'll report here the relevant fragment:

If you set this property to YES on a navigation bar with an opaque custom background image, the navigation bar will apply a system opacity less than 1.0 to the image.

查看更多
姐就是有狂的资本
7楼-- · 2019-01-02 22:13

This seems to work:

@implementation UINavigationBar (custom)
- (void)drawRect:(CGRect)rect {}
@end

navigationController.navigationBar.backgroundColor = [UIColor clearColor];
查看更多
登录 后发表回答