简体   繁体   English

透明的iOS导航栏

[英]Transparent iOS navigation bar

I'm creating an app and i've browsed on the internet and i'm wondering how they make this transparent UINavigationBar like this:我正在创建一个应用程序,我在互联网上浏览过,我想知道他们是如何像这样制作这个透明的 UINavigationBar 的:

在此处输入图像描述

I've added following like in my appdelegate:我在我的 appdelegate 中添加了以下内容:

UINavigationBar.appearance().translucent = true

but this just makes it look like following:但这只是让它看起来像下面这样:

在此处输入图像描述

How can I make the navigation bar transparent like first image?如何使导航栏像第一张图片一样透明?

You can apply Navigation Bar Image like below for Translucent.您可以为半透明应用如下所示的导航栏图像。

Objective-C:目标-C:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                     forBarMetrics:UIBarMetricsDefault]; //UIImageNamed:@"transparent.png"
self.navigationController.navigationBar.shadowImage = [UIImage new];////UIImageNamed:@"transparent.png"
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];

Swift 3:斯威夫特 3:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) //UIImage.init(named: "transparent.png")
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
    

Swift Solution快速解决方案

This is the best way that I've found.这是我找到的最好的方法。 You can just paste it into your appDelegate's didFinishLaunchingWithOptions method:您可以将其粘贴到您的appDelegate 的didFinishLaunchingWithOptions方法中:

Swift 3 / 4斯威夫特 3 / 4

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    // Sets background to a blank/empty image
    UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
    // Sets shadow (line below the bar) to a blank image
    UINavigationBar.appearance().shadowImage = UIImage()
    // Sets the translucent background color
    UINavigationBar.appearance().backgroundColor = .clear
    // Set translucent. (Default value is already true, so this can be removed if desired.)
    UINavigationBar.appearance().isTranslucent = true
    return true
}

Swift 2.0斯威夫特 2.0

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    // Sets background to a blank/empty image
    UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default)
    // Sets shadow (line below the bar) to a blank image
    UINavigationBar.appearance().shadowImage = UIImage()
    // Sets the translucent background color
    UINavigationBar.appearance().backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
    // Set translucent. (Default value is already true, so this can be removed if desired.)
    UINavigationBar.appearance().translucent = true

    return true
}

source: Make navigation bar transparent regarding below image in iOS 8.1来源: 在 iOS 8.1 中使导航栏对下面的图像透明

Swift 5 applying only to the current view controller Swift 5 仅适用于当前视图控制器

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Make the navigation bar background clear
    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
    navigationController?.navigationBar.isTranslucent = true
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    // Restore the navigation bar to default
    navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
    navigationController?.navigationBar.shadowImage = nil
}

Swift 3 : extension for Transparent Navigation Bar Swift 3:透明导航栏的扩展

extension UINavigationBar {
    func transparentNavigationBar() {
    self.setBackgroundImage(UIImage(), for: .default)
    self.shadowImage = UIImage()
    self.isTranslucent = true
    }
}

Swift 4.2 Solution: For transparent Background: Swift 4.2 解决方案:对于透明背景:

  1. For General Approach:对于一般方法:

     override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true }
  2. For Specific Object:对于特定对象:

     override func viewDidLoad() { super.viewDidLoad() navBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navBar.shadowImage = UIImage() navBar.navigationBar.isTranslucent = true }

Hope it's useful.希望它有用。

I was able to accomplish this in swift this way:我能够通过这种方式迅速完成这项工作:

let navBarAppearance = UINavigationBar.appearance()
let colorImage = UIImage.imageFromColor(UIColor.morselPink(), frame: CGRectMake(0, 0, 340, 64))
navBarAppearance.setBackgroundImage(colorImage, forBarMetrics: .Default)

where i created the following utility method in a UIColor category:我在UIColor类别中创建了以下实用程序方法:

imageFromColor(color: UIColor, frame: CGRect) -> UIImage {
  UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
  color.setFill()
  UIRectFill(frame)
  let image = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  return image
}

What it worked for me:它对我有用:

    let bar:UINavigationBar! =  self.navigationController?.navigationBar
    self.title = "Whatever..."
    bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
    bar.shadowImage = UIImage()
    bar.alpha = 0.0 

I had been working on this, and I was facing a problem using the responses provided here by different users.我一直在努力解决这个问题,但我在使用不同用户在此处提供的回复时遇到了问题。 Problem was a white box behind my NavigationBar transparent image on iOS 13+问题是在 iOS 13+ 上我的 NavigationBar 透明图像后面有一个白框

在此处输入图片说明

My solution is this one我的解决方案是这个

if #available(iOS 13, *) {
    navBar?.standardAppearance.backgroundColor = UIColor.clear
    navBar?.standardAppearance.backgroundEffect = nil
    navBar?.standardAppearance.shadowImage = UIImage()
    navBar?.standardAppearance.shadowColor = .clear
    navBar?.standardAppearance.backgroundImage = UIImage()
}

Update更新

thanks to @TMin感谢@TMin

If you use a tableView/CollectionView with this you will notice a 1 point shadow appears when you scroll.如果您使用 tableView/CollectionView,您会注意到滚动时会出现 1 点阴影。 Add navBar?.scrollEdgeAppearance = nil to get ride of this shadow.添加 navBar?.scrollEdgeAppearance = nil 来摆脱这个阴影。

Hope this helps anyone with same problem希望这可以帮助任何有同样问题的人

Set the background property of your navigationBar, eg设置导航栏的背景属性,例如

navigationController?.navigationBar.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.5)

(You may have to change that a bit if you don't have a navigation controller, but that should give you an idea of what to do.) (如果你没有导航控制器,你可能需要稍微改变一下,但这应该让你知道该怎么做。)

Also make sure that the view below actually extends under the bar.还要确保下面的视图实际上延伸到栏下方。

Add this in your did load将此添加到您的加载中

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.0)
//adjust alpha according to your need 0 is transparent 1 is solid

If you want to be able to do this programmatically in swift 4 while staying on the same view,如果您希望能够在 swift 4 中以编程方式执行此操作,同时保持相同的视图,

if change {
        navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.navigationBar.backgroundColor = UIColor(displayP3Red: 255/255, green: 206/255, blue: 24/255, alpha: 1)
        navigationController?.navigationBar.barTintColor = UIColor(displayP3Red: 255/255, green: 206/255, blue: 24/255, alpha: 1)
    } else {
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.setBackgroundImage(backgroundImage, for: .default)
        navigationController?.navigationBar.backgroundColor = .clear
        navigationController?.navigationBar.barTintColor = .clear
    }

One important thing to remember though is to click this button in your storyboard.但要记住的一件重要事情是单击故事板中的此按钮。 I had an issue with a jumping display for a long time.我有很长一段时间的跳跃显示问题。 Make sureyou set this:确保你设置了这个: 在此处输入图片说明

Then when you change the translucency of the navigation bar it will not cause the views to jump as the views extend all the way to the top, regardless of the visiblity of the navigation bar.然后,当您更改导航栏的半透明度时,无论导航栏的可见性如何,它都不会导致视图跳转,因为视图一直延伸到顶部。

Try this, it works for me if you also need to support ios7, it is based on the transparency of UItoolBar:试试这个,如果你还需要支持ios7,它对我有用,它基于UItoolBar的透明度:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.view.backgroundColor = [UIColor clearColor];
    UIToolbar* blurredView = [[UIToolbar alloc] initWithFrame:self.navigationController.navigationBar.bounds];
    [blurredView setBarStyle:UIBarStyleBlack];
    [blurredView setBarTintColor:[UIColor redColor]];
    [self.navigationController.navigationBar insertSubview:blurredView atIndex:0];

For those looking for OBJC solution, to be added in App Delegate didFinishLaunchingWithOptions method:对于那些寻找 OBJC 解决方案的人,可以在 App Delegate didFinishLaunchingWithOptions 方法中添加:

[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
[UINavigationBar appearance].backgroundColor = [UIColor clearColor];
[UINavigationBar appearance].translucent = YES;

Utility method which you call by passing navigationController and color which you like to set on navigation bar.您通过传递导航控制器和您想在导航栏上设置的颜色来调用的实用方法。 For transparent you can use clearColor of UIColor class.对于透明,您可以使用UIColor类的clearColor

For objective c -对于目标 c -

+ (void)setNavigationBarColor:(UINavigationController *)navigationController 
                               color:(UIColor*) color {
   [navigationController setNavigationBarHidden:false animated:false];
   [navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
   [navigationController.navigationBar setShadowImage:[UIImage new]];
   [navigationController.navigationBar setTranslucent:true];
   [navigationController.view setBackgroundColor:color];
   [navigationController.navigationBar setBackgroundColor:color];
}

For Swift 3.0 -对于 Swift 3.0 -

class func setNavigationBarColor(navigationController : UINavigationController?, 
                                 color : UIColor) {
    navigationController?.setNavigationBarHidden(false, animated: false)
    navigationController?.navigationBar .setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
    navigationController?.navigationBar.shadowImage = UIImage()
    navigationController?.navigationBar.translucent = true
    navigationController?.view.backgroundColor = color
    navigationController?.navigationBar.backgroundColor =  color
}

Write these two lines:写下这两行:

 navigationController?.navigationBar.isTranslucent = true
 navigationController?.navigationBar.backgroundColor = .clear

Worked for me in iOS 13在 iOS 13 中为我工作

None of the answers here fully worked for me.这里没有一个答案完全适合我。 This makes the navigation bar fully transparent - tested on iOS 14 and iOS 11 (Objective C):这使得导航栏完全透明 - 在 iOS 14 和 iOS 11(目标 C)上测试:

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

iOS 13.0+ introduced UINavigationBarAppearance because of which, this problem occurs on iOS 13.0+ iOS 13.0+ 引入了 UINavigationBarAppearance,因此在 iOS 13.0+ 上会出现这个问题

Use this to solve.用这个来解决。

Change Navigation Bar Appearance Use UINavigationBarAppearance and UIBarButtonItemAppearance to change the appearance of the navigation bar.更改导航栏外观 使用 UINavigationBarAppearance 和 UIBarButtonItemAppearance 来更改导航栏的外观。

// Make the navigation bar's title with red text. // 用红色文本制作导航栏的标题。

if #available(iOS 13, *) {
        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundColor = UIColor.systemRed
        appearance.titleTextAttributes = [.foregroundColor: UIColor.lightText] // With a red background, make the title more readable.
        navigationItem.standardAppearance = appearance
        navigationItem.scrollEdgeAppearance = appearance
        navigationItem.compactAppearance = appearance // For iPhone small navigation bar in landscape.
    }

Anyone looking for a iOS 15+ working version, this is what worked for me, as the old techniques with setBackgroundImage / shadowImage were not working anymore.任何正在寻找 iOS 15+ 工作版本的人,这对我shadowImage ,因为setBackgroundImage / shadowImage的旧技术不再有效。

To se it transparent:设置透明:

func setTransparent() {
    backgroundColor = .clear
    isTranslucent = true

    standardAppearance.shadowColor = .clear
    standardAppearance.backgroundColor = .clear
    standardAppearance.backgroundEffect = nil
    scrollEdgeAppearance = standardAppearance
}

To remove transparency:要删除透明度:

func removeTransparent() {
    setBackgroundImage(nil, for: .default)
    shadowImage = nil
    backgroundColor = .white
    isTranslucent = false

    let appearance = UINavigationBarAppearance()
    appearance.configureWithOpaqueBackground()
    standardAppearance = appearance
    scrollEdgeAppearance = standardAppearance
}

My implementation of navigation bar configuration as translucent and switching to default state for iOS 15 and older versions:我将导航栏配置实现为半透明并切换到 iOS 15 及更早版本的默认状态:

extension UINavigationBar {
    static let defaultBackgroundColor = UIColor.red
    static let defaultTintColor = UIColor.white
    
    func setTranslucent(tintColor: UIColor, titleColor: UIColor) {
        if #available(iOS 15, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithTransparentBackground()
            appearance.titleTextAttributes = [.foregroundColor: titleColor]
            standardAppearance = appearance
            scrollEdgeAppearance = appearance
        } else {
            titleTextAttributes = [.foregroundColor: titleColor]
            setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            shadowImage = UIImage()
        }
        isTranslucent = true
        self.tintColor = tintColor
    }
    
    func setDefaultState() {
        isTranslucent = false
        clipsToBounds = false
        
        if #available(iOS 15, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = UINavigationBar.defaultBackgroundColor
            appearance.titleTextAttributes = [.foregroundColor: UINavigationBar.defaultTintColor]
            
            UINavigationBar.appearance().standardAppearance = appearance
            UINavigationBar.appearance().scrollEdgeAppearance = appearance
        } else {
            setBackgroundImage(UIImage(), for: UIBarPosition.any, barMetrics: UIBarMetrics.defaultPrompt)
            shadowImage = UIImage()
            barTintColor = UINavigationBar.defaultBackgroundColor
            titleTextAttributes = [.foregroundColor: UINavigationBar.defaultTintColor]
        }
        
        tintColor = UINavigationBar.defaultTintColor
    }
}

This will defiantly work for swift 4/5 users.这对 swift 4/5 的用户来说非常有效。

func setUpNavBar(){
    navigationItem.title = "Flick"
    navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = UIColor.clear
    navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
}

IOS15 Version IOS15版本

extension UIViewController {

    func clearNavigationBar(clear: Bool) {
        if clear {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithTransparentBackground()
            self.navigationController?.navigationBar.standardAppearance = appearance
            self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
        } else {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            self.navigationController?.navigationBar.standardAppearance = appearance
            self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
        }
    }
}


class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
         clearNavigationBar(clear: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
         clearNavigationBar(clear: false)
    }
}

For above all iOS version对于以上所有 iOS 版本

if #available(iOS 15.0, *) {
        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundImage = UIColor.clear.imageWithColor(width: UIScreen.main.bounds.size.width, height: 84)
        appearance.shadowImage = UIImage()
        appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black ,NSAttributedString.Key.font : UIFont(name: "SF UI Display Semibold", size: 18) ?? UIFont()]
        appearance.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 2)
        self.navigationBar.standardAppearance = appearance
    } else {
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black ,NSAttributedString.Key.font : UIFont(name: "SF UI Display Semibold", size: 18) ?? UIFont()]
        self.navigationBar.setTitleVerticalPositionAdjustment(2, for: UIBarMetrics.default)
    }


func imageWithColor(width: CGFloat, height: CGFloat) -> UIImage {
    let size = CGSize(width: width, height: height)
    return UIGraphicsImageRenderer(size: size).image { rendererContext in
        self.setFill()
        rendererContext.fill(CGRect(origin: .zero, size: size))
    }
}

Just add bellow code line inside your application delegate只需在您的应用程序委托中添加以下代码行

       UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

       // Sets shadow (line below the bar) to a blank image
       UINavigationBar.appearance().shadowImage = UIImage()

       // Sets the translucent background color
       UINavigationBar.appearance().backgroundColor = .clear
       // Set translucent. (Default value is already true, so this can be removed if desired.)

       UINavigationBar.appearance().isTranslucent = true

then override your custom nav bar inside your view controller and make sure to reset once it disappear然后覆盖视图控制器内的自定义导航栏,并确保在它消失后重置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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