Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the background or the color in the navigation bar be changed?

Currently I couldn't find any method to change the color/background of the navigation bar in SwiftUI. Any tips?

like image 662
Alberto Penas Avatar asked Jun 26 '19 13:06

Alberto Penas


2 Answers

In order to change color of navigation bar for all view controllers, you have to set it in AppDelegate.swift file

Add following code to didFinishLaunchingWithOptions function in AppDelegate.swift

var navigationBarAppearace = UINavigationBar.appearance()

navigationBarAppearace.tintColor = uicolorFromHex(0xffffff)
navigationBarAppearace.barTintColor = uicolorFromHex(0x034517)

In here tintColor attribute change the background color of the navigation bar.

barTintColor attribute affect to the color of the:

  • back indicator image
  • button titles
  • button images

Bonus:

Change color of navigation bar title:

// change navigation item title color
navigationBarAppearace.titleTextAttributes =[NSForegroundColorAttributeName:UIColor.whiteColor()]

titleTextAttributes affect to the title text

I hope it helps. :)

like image 134
Max Vinicius Avatar answered Dec 15 '22 00:12

Max Vinicius


In SwiftUI, at this point we can not change it directly, but you can change navigationBar appearance like this,

struct YourView: View {
    init() {
        UINavigationBar.appearance().backgroundColor = .orange

        //Use this if NavigationBarTitle is with Large Font
        UINavigationBar.appearance().largeTitleTextAttributes = [.font : UIFont(name: "Georgia-Bold", size: 20)!]

        //Use this if NavigationBarTitle is with displayMode = .inline
        //UINavigationBar.appearance().titleTextAttributes = [.font : UIFont(name: "Georgia-Bold", size: 20)!]
    }

    var body: some View {
        NavigationView {
            Text("Hello World!")
              .navigationBarTitle(Text("Dashboard").font(.subheadline), displayMode: .large)
            //.navigationBarTitle (Text("Dashboard"), displayMode: .inline)
        }
    }
}

I hope this will help you. Thanks!!

like image 25
Anjali Kevadiya Avatar answered Dec 15 '22 00:12

Anjali Kevadiya