ios 在 Swift 中更改导航栏颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24687238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:19:53  来源:igfitidea点击:

Changing navigation bar color in Swift

iosswiftuinavigationbar

提问by user3746428

I am using a Picker View to allow the user to choose the colour theme for the entire app.

我正在使用 Picker View 来允许用户为整个应用程序选择颜色主题。

I am planning on changing the colour of the navigation bar, background and possibly the tab bar (if that is possible).

我计划更改导航栏、背景和标签栏的颜色(如果可能的话)。

I've been researching how to do this but can't find any Swift examples. Could anyone please give me an example of the code I would need to use to change the navigation bar colour and navigation bar text colour?

我一直在研究如何做到这一点,但找不到任何 Swift 示例。谁能给我一个我需要用来更改导航栏颜色和导航栏文本颜色的代码示例?

The Picker View is set up, I'm just looking for the code to change the UI colours.

选择器视图已设置,我只是在寻找更改 UI 颜色的代码。

回答by trumpeter201

Navigation Bar:

导航栏:

navigationController?.navigationBar.barTintColor = UIColor.green

Replace greenColor with whatever UIColor you want, you can use an RGB too if you prefer.

用你想要的任何 UIColor 替换 greenColor,如果你愿意,你也可以使用 RGB。

Navigation Bar Text:

导航栏文字:

navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange]

Replace orangeColor with whatever color you like.

用你喜欢的任何颜色替换 orangeColor。

Tab Bar:

标签栏:

tabBarController?.tabBar.barTintColor = UIColor.brown

Tab Bar Text:

标签栏文本:

tabBarController?.tabBar.tintColor = UIColor.yellow

On the last two, replace brownColor and yellowColor with the color of your choice.

在最后两个中,用您选择的颜色替换 brownColor 和 yellowColor。

回答by Keenle

Here are some very basic appearance customization that you can apply app wide:

以下是一些非常基本的外观自定义,您可以在应用程序范围内应用它们:

UINavigationBar.appearance().backgroundColor = UIColor.greenColor()
UIBarButtonItem.appearance().tintColor = UIColor.magentaColor()
//Since iOS 7.0 UITextAttributeTextColor was replaced by NSForegroundColorAttributeName
UINavigationBar.appearance().titleTextAttributes = [UITextAttributeTextColor: UIColor.blueColor()]
UITabBar.appearance().backgroundColor = UIColor.yellowColor();

More about UIAppearanceAPI in Swift you can read here: https://developer.apple.com/documentation/uikit/uiappearance

UIAppearance您可以在此处阅读有关Swift API 的更多信息:https: //developer.apple.com/documentation/uikit/uiappearance

回答by Jamil Hasnine Tamim

Updated for Swift 3, 4, 4.2, 5+

为 Swift 3、4、4.2、5+ 更新

// setup navBar.....
UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
UINavigationBar.appearance().isTranslucent = false

Swift 4

斯威夫特 4

UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false

Swift 4.2, 5+

斯威夫特 4.2, 5+

UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false

Also can check here : https://github.com/hasnine/iOSUtilitiesSource

也可以在这里查看:https: //github.com/hasnine/iOSUtilitiesSource

回答by Mohit Tomar

UINavigationBar.appearance().barTintColor = UIColor(red: 46.0/255.0, green: 14.0/255.0, blue: 74.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

Just paste this line in didFinishLaunchingWithOptionsin your code.

只需将此行粘贴didFinishLaunchingWithOptions到您的代码中即可。

回答by David West

Within AppDelegate, this has globally changed the format of the NavBar and removes the bottom line/border (which is a problem area for most people) to give you what I think you and others are looking for:

AppDelegate 中,这已经全局更改了 NavBar 的格式并删除了底线/边框(这是大多数人的问题区域),为您提供我认为您和其他人正在寻找的内容:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().tintColor = UIColor.whiteColor()
    UINavigationBar.appearance().barTintColor = Style.SELECTED_COLOR
    UINavigationBar.appearance().translucent = false
    UINavigationBar.appearance().clipsToBounds = false
    UINavigationBar.appearance().backgroundColor = Style.SELECTED_COLOR
    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : (UIFont(name: "FONT NAME", size: 18))!, NSForegroundColorAttributeName: UIColor.whiteColor()] }

Then you can setup a Constants.swiftfile, and contained is a Style struct with colors and fonts etc. You can then add a tableView/pickerView to any ViewController and use "availableThemes" array to allow user to change themeColor.

然后你可以设置一个Constants.swift文件,其中包含一个带有颜色和字体等的 Style 结构。然后你可以将 tableView/pickerView 添加到任何 ViewController 并使用“availableThemes”数组来允许用户更改 themeColor。

The beautiful thing about this is you can use one reference throughout your whole app for each colour and it'll update based on the user's selected "Theme" and without one it defaults to theme1():

这样做的好处在于,您可以在整个应用程序中为每种颜色使用一个参考,它将根据用户选择的“主题”进行更新,如果没有,则默认为 theme1():

import Foundation
import UIKit

struct Style {


static let availableThemes = ["Theme 1","Theme 2","Theme 3"]

static func loadTheme(){
    let defaults = NSUserDefaults.standardUserDefaults()
    if let name = defaults.stringForKey("Theme"){
        // Select the Theme
        if name == availableThemes[0]   { theme1()  }
        if name == availableThemes[1]   { theme2()  }
        if name == availableThemes[2]   { theme3()  }
    }else{
        defaults.setObject(availableThemes[0], forKey: "Theme")
        theme1()
    }
}

 // Colors specific to theme - can include multiple colours here for each one
static func theme1(){
   static var SELECTED_COLOR = UIColor(red:70/255, green: 38/255, blue: 92/255, alpha: 1) }

static func theme2(){
    static var SELECTED_COLOR = UIColor(red:255/255, green: 255/255, blue: 255/255, alpha: 1) }

static func theme3(){
    static var SELECTED_COLOR = UIColor(red:90/255, green: 50/255, blue: 120/255, alpha: 1) } ...

回答by Fangming

To do this on storyboard (Interface Builder Inspector)

要在故事板(Interface Builder Inspector)上执行此操作

With help of IBDesignable, we can add more options to Interface Builder Inspector for UINavigationControllerand tweak them on storyboard. First, add the following code to your project.

在 的帮助下IBDesignable,我们可以为 Interface Builder Inspector 添加更多选项UINavigationController并在故事板上调整它们。首先,将以下代码添加到您的项目中。

@IBDesignable extension UINavigationController {
    @IBInspectable var barTintColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            navigationBar.barTintColor = uiColor
        }
        get {
            guard let color = navigationBar.barTintColor else { return nil }
            return color
        }
    }
}

Then simply set the attributes for navigation controller on storyboard.

然后只需在情节提要上设置导航控制器的属性。

enter image description here

在此处输入图片说明

This approach may also be used to manage the color of the navigation bar text from the storyboard:

这种方法也可用于管理故事板中导航栏文本的颜色:

@IBInspectable var barTextColor: UIColor? {
  set {
    guard let uiColor = newValue else {return}
    navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: uiColor]
  }
  get {
    guard let textAttributes = navigationBar.titleTextAttributes else { return nil }
    return textAttributes[NSAttributedStringKey.foregroundColor] as? UIColor
  }
}

回答by Gaurav Singla

Swift 4:

斯威夫特 4:

Perfectly working code to change the navigation bar appearance at application level.

在应用程序级别更改导航栏外观的完美工作代码。

enter image description here

在此处输入图片说明

// MARK: Navigation Bar Customisation

// To change background colour.
UINavigationBar.appearance().barTintColor = .init(red: 23.0/255, green: 197.0/255, blue: 157.0/255, alpha: 1.0)

// To change colour of tappable items.
UINavigationBar.appearance().tintColor = .white

// To apply textAttributes to title i.e. colour, font etc.
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : UIColor.white,
                                                    .font : UIFont.init(name: "AvenirNext-DemiBold", size: 22.0)!]
// To control navigation bar's translucency.
UINavigationBar.appearance().isTranslucent = false

Happy Coding!

快乐编码!

回答by Asbar

UINavigationBar.appearance().barTintColor

worked for me

为我工作

回答by ricks

SWIFT 4 - Smooth transition (best solution):

SWIFT 4 - 平滑过渡(最佳解决方案):

If you're moving back from a navigation controller and you have to set a diffrent color on the navigation controller you pushed from you want to use

如果您要从导航控制器返回,并且必须在要使用的导航控制器上设置不同的颜色

override func willMove(toParentViewController parent: UIViewController?) {
    navigationController?.navigationBar.barTintColor = .white
    navigationController?.navigationBar.tintColor = Constants.AppColor
}

instead of putting it in the viewWillAppear so the transition is cleaner.

而不是把它放在 viewWillAppear 中,所以过渡更干净。

SWIFT 4.2

斯威夫特 4.2

override func willMove(toParent parent: UIViewController?) {
    navigationController?.navigationBar.barTintColor = UIColor.black
    navigationController?.navigationBar.tintColor = UIColor.black
}

回答by Vinoth Vino

In Swift 4

斯威夫特 4

You can change the color of navigation bar. Just use this below code snippet in viewDidLoad()

您可以更改导航栏的颜色。只需使用下面的代码片段viewDidLoad()

Navigation Bar color

导航栏颜色

self.navigationController?.navigationBar.barTintColor = UIColor.white

Navigation Bar Text Color

导航栏文字颜色

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]

For iOS 11 Large Title Navigation Bar, you need to use largeTitleTextAttributesproperty

对于iOS 11 大标题导航栏,您需要使用largeTitleTextAttributes属性

self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]