Zmiana koloru paska nawigacji w Swift

Używam widoku selektora, aby umożliwić użytkownikowi wybór motywu kolorów dla całej aplikacji. Planuję zmienić kolor paska nawigacji, tła i ewentualnie paska kart (Jeśli to możliwe). Badałem, jak to zrobić, ale nie mogę znaleźć żadnych szybkich przykładów. Czy ktoś mógłby mi podać przykład kodu, którego potrzebowałbym użyć do zmiany koloru paska nawigacji i koloru tekstu paska nawigacji? (Widok selektora jest ustawiony, Szukam tylko kodu do zmiany kolory UI)

Dzięki.
Author: narner, 2014-07-11

22 answers

Pasek Nawigacji:

navigationController?.navigationBar.barTintColor = UIColor.green

Zastąp greenColor dowolnym Uicolorem, możesz też użyć RGB, jeśli wolisz.

Tekst Paska Nawigacyjnego:

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

Zastąp orangeColor dowolnym kolorem.

Pasek Tabulacji:

tabBarController?.tabBar.barTintColor = UIColor.brown

Tekst Paska Kart:

tabBarController?.tabBar.tintColor = UIColor.yellow

Na dwóch ostatnich, zastąp brownColor i yellowColor kolorem do wyboru.

 358
Author: trumpeter201,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-13 19:41:25

Oto kilka bardzo podstawowych ustawień wyglądu, które można zastosować w całej aplikacji:

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();

Więcej o UIAppearance API w języku Swift przeczytasz tutaj: https://developer.apple.com/documentation/uikit/uiappearance

 73
Author: Keenle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-29 13:17:52
    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()]

Po prostu wklej ten wiersz w didFinishLaunchingWithOptions w swoim kodzie.

 46
Author: Mohit tomar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-10 07:24:18

Wewnątrz AppDelegate , to globalnie zmieniło format paska nawigacyjnego i usuwa dolną linię / granicę (która jest obszarem problemowym dla większości ludzi), aby dać ci to, co myślę, że ty i inni szukacie:

 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()] }

Następnie możesz ustawić Stałe.plik swift , a zawarty w nim jest strukturą stylu z kolorami i czcionkami itp. Następnie możesz dodać tableView/pickerView do dowolnego kontrolera ViewController i użyć tablicy" availableThemes", aby umożliwić użytkownikowi zmianę koloru.

The piękne w tym jest to, że możesz użyć jednego odniesienia w całej aplikacji dla każdego koloru i zaktualizuje się w oparciu o wybrany przez użytkownika "motyw" i bez niego domyślnie 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) } ...
 23
Author: David West,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-20 15:53:44
UINavigationBar.appearance().barTintColor

Pracował dla mnie

 15
Author: Asbar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-23 18:16:28

Aktualizacja dla Swift 3

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

Swift 4

UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false
 15
Author: Jamil Hasnine Tamim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-01 05:40:30

Aby to zrobić na storyboard (Interface Builder Inspector)

Z pomocą IBDesignable możemy dodać więcej opcji do Inspektora konstruktora interfejsu dla UINavigationController i dostosować je na storyboardzie. Najpierw dodaj poniższy kod do swojego projektu.

@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
        }
    }
}

Następnie po prostu ustaw atrybuty kontrolera nawigacyjnego na storyboardzie.

Tutaj wpisz opis obrazka

To podejście może być również używane do zarządzania kolorem tekstu paska nawigacyjnego ze storyboardu:

@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
  }
}
 15
Author: Fangming,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-03 18:01:25

Użyj interfejsu API appearance I koloru barintcolor.

UINavigationBar.appearance().barTintColor = UIColor.greenColor()
 7
Author: Michael Peterson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-11 18:47:59

Funkcja appearance() nie zawsze działa dla mnie. Wolę więc tworzyć obiekt NC i zmieniać jego atrybuty.

var navBarColor = navigationController!.navigationBar
        navBarColor.barTintColor = UIColor(red:  255/255.0, green: 0/255.0, blue: 0/255.0, alpha: 100.0/100.0)
        navBarColor.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]

Również jeśli chcesz dodać obraz zamiast tylko tekstu, to działa również

var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
        imageView.contentMode = .ScaleAspectFit

        var image = UIImage(named: "logo")
        imageView.image = image
        navigationItem.titleView = imageView
 7
Author: GuiSoySauce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-30 02:36:44

In Swift 4

Możesz zmienić kolor paska nawigacyjnego. Wystarczy użyć poniższego fragmentu kodu w viewDidLoad()

Kolor paska nawigacyjnego

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

Kolor Tekstu Paska Nawigacyjnego

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

Dla IOS 11 duży pasek nawigacji tytułu , musisz użyć właściwości largeTitleTextAttributes

self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]
 5
Author: Vinoth Vino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-07 12:30:04

IOS 8 (swift)

let font: UIFont = UIFont(name: "fontName", size: 17)   
let color = UIColor.backColor()
self.navigationController?.navigationBar.topItem?.backBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: font,NSForegroundColorAttributeName: color], forState: .Normal)
 4
Author: Long Pham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-22 07:29:17

Jeśli masz dostosowany Kontroler nawigacyjny, możesz użyć powyższego fragmentu kodu. Więc w moim przypadku, użyłem jako następujące kawałki kodu.

Swift 3.0, Xcode 8.1 version

navigationController.navigationBar.barTintColor = UIColor.green

Tekst Paska Nawigacyjnego:

navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]
To bardzo pomocne rozmowy.
 4
Author: Bogdan Dimitrov Filov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-18 11:04:07

Swift 4:

Doskonale działający kod umożliwiający zmianę wyglądu paska nawigacyjnego na poziomie aplikacji.

Tutaj wpisz opis obrazka

// 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
Szczęśliwego Kodowania!
 4
Author: Gaurav Singla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-02 19:30:58

In Swift 2

Do zmiany koloru na pasku nawigacyjnym,

navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

Do zmiany koloru w pasku nawigacyjnym pozycji,

navigationController?.navigationBar.tintColor = UIColor.blueColor()

Lub

navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blueColor()]
 3
Author: Riccardo Caroli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-28 16:50:09

Swift 3

UINavigationBar.appearance().barTintColor = UIColor(colorLiteralRed: 51/255, green: 90/255, blue: 149/255, alpha: 1)

To ustawi kolor paska nawigacyjnego jak kolor paska Facebook:)

 3
Author: Sazzad Hissain Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-13 04:06:25

Swift 3 i Swift 4 kompatybilne Xcode 9

Lepszym rozwiązaniem jest stworzenie klasy dla wspólnych pasków nawigacyjnych

Mam 5 kontrolerów i każdy tytuł kontrolera jest zmieniany na pomarańczowy kolor. Ponieważ każdy kontroler ma Kontrolery nawigacyjne 5, więc musiałem zmienić każdy kolor z inspektora lub z kodu.

Więc zrobiłem klasę zamiast zmieniać każdy pasek nawigacyjny z kodu po prostu przypisałem tę klasę i działało na wszystkich 5 możliwość ponownego użycia kodu kontrolera. Musisz tylko przypisać tę klasę do każdego kontrolera i to wszystko.

import UIKit

   class NabigationBar: UINavigationBar {
      required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    commonFeatures()
 }

   func commonFeatures() {

    self.backgroundColor = UIColor.white;
      UINavigationBar.appearance().titleTextAttributes =     [NSAttributedStringKey.foregroundColor:ColorConstants.orangeTextColor]

 }


  }
 3
Author: Ourang-Zeb Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-22 11:48:57

Aktualizacja Swift 4, iOS 12 i Xcode 10

Wystarczy umieścić jedną linię wewnątrz viewDidLoad()

navigationController?.navigationBar.barTintColor = UIColor.red
 3
Author: Xcodian Solangi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-10 09:59:53

SWIFT 4-płynne przejście (najlepsze rozwiązanie):

Jeśli cofasz się z kontrolera nawigacyjnego i musisz ustawić inny kolor na kontrolerze nawigacyjnym, z którego chcesz korzystać

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

Zamiast umieszczać go w widoku, aby przejście było czystsze.

 3
Author: RickS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-02 19:11:10

IOS 10 Swift 3.0

Jeśli nie masz nic przeciwko użyciu frameworków swift, to my UINeraida aby zmienić tło nawigacji jako UIColor lub HexColor lub UIImage i programowo zmienić tekst przycisku nawigacyjnego wstecz, Zmień kolor tekstu.

Na UINavigationBar

    neraida.navigation.background.color.hexColor("54ad00", isTranslucent: false, viewController: self)

    //Change navigation title, backbutton colour

    neraida.navigation.foreground.color.uiColor(UIColor.white, viewController: self)

    //Change navigation back button title programmatically

    neraida.navigation.foreground.backButtonTitle("Custom Title", ViewController: self)

    //Apply Background Image to the UINavigationBar

    neraida.navigation.background.image("background", edge: (0,0,0,0), barMetrics: .default, isTranslucent: false, viewController: self)
 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-16 00:52:03

Swift 3

Prosta jedna wkładka, którą możesz użyć w ViewDidLoad()

//Change Color
    self.navigationController?.navigationBar.barTintColor = UIColor.red
//Change Text Color
    self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
 2
Author: Satnam Sync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-21 07:50:44

I had to do

UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().barStyle = .Black
UINavigationBar.appearance().backgroundColor = UIColor.blueColor()

Inaczej kolor tła by się nie zmienił

 1
Author: Guilherme Carvalho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-20 10:30:30

Najpierw ustaw właściwość istranslucent w navigationBar na false, aby uzyskać żądany kolor. Następnie zmień kolor paska nawigacyjnego w następujący sposób:

@IBOutlet var NavigationBar: UINavigationBar!

NavigationBar.isTranslucent = false
NavigationBar.barTintColor = UIColor (red: 117/255, green: 23/255, blue: 49/255, alpha: 1.0)
 1
Author: Nupur Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-10 05:22:31