SwiftUI TabBar Color - swiftui

How can one set the tabbar color? Assigning the color black results only with a grey bar for example.
This is for SwiftUI.
Specify dark mode is not a suitable work around.
struct ContentView: View {
#State private var selection = 1
init() {
UITabBar.appearance().backgroundColor = UIColor.blue
UITabBar.appearance().backgroundImage = UIImage()
//UITabBar.appearance().isTranslucent = false
//UITabBar.appearance().shadowImage = UIImage()
}
var body: some View {
TabView {
ClockView()
.tabItem {
Image("clock")
Text("Clock")
}.tag(0)
PlanetsNowView()
.tabItem {
Image("clock")
Text("Now")
}.tag(1)
SettingsView()
.tabItem {
Image("settings")
Text("Settings")
}.tag(2)
}
.accentColor(.white)
.opacity(1)
//.environment(\.colorScheme, .dark)
}
}

This is the initializer to create a black tab bar in your SwiftUI View.
import SwiftUI
struct ContentView: View {
init() {
setupTabBar()
}
var body: some View {
TabView {
//Your tab bar items
}
}
}
//MARK: - Tab bar view appearance
extension ContentView {
func setupTabBar() {
UITabBar.appearance().barTintColor = .black
UITabBar.appearance().tintColor = .blue
UITabBar.appearance().layer.borderColor = UIColor.clear.cgColor
UITabBar.appearance().clipsToBounds = true
}
}
If you want to change the color depending on the user light/dark mode settings:
Open 'Assets.xcassets' folder
Right click on your assets panel
Choose 'New Color Set'
Open your attribute inspector panel of the new color
Select 'Appearances'
Choose 'Any, Dark'
You will have now two colored squares where you have to choose your light mode color for the first one, and the dark mode one for the second one.
To use it in your code while initializing your tab bar, change the line that defines the barTintColor with the name of your new set of light/dark mode color.
UITabBar.appearance().barTintColor = UIColor(named: "<your color name>")

Add UITabBar.appearance().barTintColor = UIColor.blue in the initialiser.
Not be found in Xcode code assist however.
struct ContentView: View {
#State private var selection = 1
init() {
UITabBar.appearance().barTintColor = UIColor.blue
UITabBar.appearance().tintColor = .green
}
var body: some View {
TabView (selection:$selection){
Text("The First Tab")
.tabItem {
Image(systemName: "1.square.fill")
Text("First")
}
.tag(1)
Text("Another Tab")
.tabItem {
Image(systemName: "2.square.fill")
Text("Second")
}.tag(2)
Text("The Last Tab")
.tabItem {
Image(systemName: "3.square.fill")
Text("Third")
}.tag(3)
}
.font(.headline)
.accentColor(.white)
}
}

Related

SwiftUI TabView repeats first entry

Xcode RC 14.1
The first tab is generated twice. The first one works, the second brings up a blank screen. This has been reported elsewhere on SO and people suggest removing Spacer()s but this made no difference.
The code below has two variants, one with a enum for the tag as opposed to an integer but they both misbehave identically. (Not sure why all the code hasn't ended up grey below?)
import SwiftUI
struct MenuView: View {
private enum Tab: Hashable {
case location
case calculate
case install
case results
case about
}
// #State private var tabBarSelected: Tab = .location
#State private var selectedTab = 0
var body: some View {
VStack {
TabView(selection: $selectedTab) {
LocationView()
// .tag(Tab.location)
.tag(0)
.tabItem {
Text("Location")
Image(systemName: "globe.europe.africa")
}
CalculateView()
// .tag(Tab.calculate)
.tag(1)
.tabItem {
Text("Calculate")
Image(systemName: "apps.ipad")
}
InstallView()
// .tag(Tab.install)
.tag(2)
.tabItem {
Text("Install")
Image(systemName: "window.ceiling.closed")
}
ResultsView()
.tag(3)
// .tag(Tab.results)
.tabItem {
Text("Results")
Image(systemName: "sun.max.fill")
}
AboutView()
.tag(4)
// .tag(Tab.about)
.tabItem {
Text("About")
Image(systemName: "gear")
}
} // TabView
.accentColor(.yellow) //Active tab color
} // VStack
} // body
init() {
UITabBar.appearance().barTintColor = UIColor.systemGray //TabBar color
UITabBar.appearance().unselectedItemTintColor = UIColor.systemGray2
UITabBar.appearance().isOpaque = false
}
}
struct MenuView_Previews: PreviewProvider {
static var previews: some View {
MenuView()
}
}
You need to wrap your content in a VStack, kindly check your code in LocationView().
Instead of this:
var body: some View {
Text("Hi")
Text("welcome")
}
Use the code below:
var body: some View {
VStack {
Text("Hi")
Text("welcome")
}
}

TabView Label doesn't appear while the background color doesn't fill the entire screen

This is my reproducible code.
Problems: There is no error in my code but I can't find my TabView Label. The background was declared with .ignoresSafeArea(.all) but still doesn't fill the entire screen.
import SwiftUI
struct LibraryView: View {
var allColors: [Color] = [Color.red, Color.green, Color.blue]
var body: some View {
TabView {
ForEach(allColors, id: \.self) { color in
BookSubView(bColor: color)
.tabItem {
Text("BOOK")
.foregroundColor(color)
Image(systemName: "book")
}
}
}
.tabViewStyle(.page)
}
}
struct BookSubView: View {
var bColor: Color
var body: some View {
LinearGradient(colors: [bColor, Color.white], startPoint: .top,
endPoint: .bottom).ignoresSafeArea(.all)
}
}
Use a Label inside of the .tabItem modifier
BookSubView(bColor: color)
.tabItem {
// There are probably modifiers for Label you can use to customize to your needs
Label("Book", systemImage: "book")
}

SwiftUI changing navigation bar background color for inline navigationBarTitleDisplayMode

I just started coding in SwiftUI and came across a problem. I need to give different colors to the background of the navigation bar (NavigationView). The colors will change as I go from one view to the next. I need to have this working for navigationBarTitleDisplayMode being "inline".
I tried the solutions presented in:
SwiftUI update navigation bar title color
but none of these solutions work fully for what I need.
The solution in this reply to that post works for inline:
Using UIViewControllerRepresentable. Nevertheless, when we first open the view it will show the color of the previous view for one second, before changing to the new color. I would like to avoid this and have the color displayed as soon as everything appears on screen. Is there a way to do this?
This other solution will not work either: Changing UINavigation's appearance in init(), because when I set the background in init(), it will change the background of all the views in the app. Again, I need the views to have different background colors.
I tried something similar to this solution: Modifying Toolbar, but it does not allow me to change the color of the navigation bar.
The other solution I tried was this: Creating navigationBarColor function, which is based on: NAVIGATIONVIEW DYNAMIC BACKGROUND COLOR IN SWIFTUI. This solution works for navigationBarTitleDisplayMode "large", but when setting navigationBarTitleDisplayMode to "inline", it will show the background color of the navigation bar in a different color, as if it was covered by a gray/transparent layer. For example, the color it shows in "large" mode is:
Red color in large mode
But instead, it shows this color:
Red color in inline mode
Finally, I tried this solution: Subclassing UIViewController and configuring viewDidLayoutSubviews(), but it did not work for what I want it either.
The closest solutions for what I need are 1. and 4., but they still do not work 100%.
Would anybody know how to make any of these solutions work for navigationBarTitleDisplayMode inline, being able to change the background color of the navigation bar in different layouts, and showing the new color once the view is shown (without delays)?
Thank you!
By the way, I am using XCode 12.5.
Here is the sample code that I am using, taking example 4. as a model:
FirstView.swift
import SwiftUI
struct FirstView: View {
#State private var selection: String? = nil
var body: some View {
NavigationView {
GeometryReader { metrics in
VStack {
Text("This is the first view")
NavigationLink(destination: SecondView(), tag: "SecondView", selection: $selection) {
EmptyView()
}
Button(action: {
self.selection = "SecondView"
print("Go to second view")
}) {
Text("Go to second view")
}
}
}
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
SecondView.swift
On this screen, if I use
.navigationBarTitleDisplayMode(.large)
the color will be displayed properly: Navigation bar with red color
But using
.navigationBarTitleDisplayMode(.inline)
there is a blur on it: Navigation bar with some sort of blur over red color
import SwiftUI
struct SecondView: View {
#State private var selection: String? = nil
var body: some View {
GeometryReader { metrics in
VStack {
Text("This is the second view")
NavigationLink(destination: ThirdView(), tag: "ThirdView", selection: $selection) {
EmptyView()
}
Button(action: {
self.selection = "ThirdView"
print("Go to third view")
}) {
Text("Go to third view")
}
}
}
.navigationBarColor(backgroundColor: Color.red, titleColor: .black)
.navigationBarTitleDisplayMode(.inline)
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
ThirdView.swift
This view displays the color properly as it is using
.navigationBarTitleDisplayMode(.large)
But if changed to
.navigationBarTitleDisplayMode(.inline)
it will show the blur on top of the color as well.
import SwiftUI
struct ThirdView: View {
var body: some View {
GeometryReader { metrics in
Text("This is the third view")
}
.navigationBarColor(backgroundColor: Color.blue, titleColor: .black)
.navigationBarTitleDisplayMode(.large)
}
}
struct ThirdView_Previews: PreviewProvider {
static var previews: some View {
ThirdView()
}
}
NavigationBarModifierView.swift
import SwiftUI
struct NavigationBarModifier: ViewModifier {
var backgroundColor: UIColor?
var titleColor: UIColor?
init(backgroundColor: Color, titleColor: UIColor?) {
self.backgroundColor = UIColor(backgroundColor)
let coloredAppearance = UINavigationBarAppearance()
coloredAppearance.configureWithTransparentBackground()
coloredAppearance.backgroundColor = UIColor(backgroundColor)
coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]
coloredAppearance.shadowColor = .clear
UINavigationBar.appearance().standardAppearance = coloredAppearance
UINavigationBar.appearance().compactAppearance = coloredAppearance
UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
UINavigationBar.appearance().tintColor = titleColor
}
func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
Color(self.backgroundColor ?? .clear)
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
extension View {
func navigationBarColor(backgroundColor: Color, titleColor: UIColor?) -> some View {
self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
}
}
NOTE TO THE MODERATORS: Please, do not delete this post. I know similar questions were asked before, but I need an answer to this in particular which was not addressed. Please read before deleting indiscriminately, I need this for work. Also, I cannot ask questions inline in each of those solutions because I do not have the minimum 50 points in stackoverflow required to write there.
I think I have what you want. It is VERY touchy... It is a hack, and not terribly robust, so take as is...
I got it to work by having your modifier return a clear NavBar, and then the solution from this answer works for you. I even added a ScrollView to ThirdView() to make sure that scrolling under didn't affect in. Also note, you lose all of the other built in effects of the bar like translucency, etc.
Edit: I went over the code. The .navigationViewStyle was in the wrong spot. It likes to be outside of the NavigaionView(), where everything else needs to be inside. Also, I removed the part of the code setting the bar color in FirstView() as it was redundant and ugly. I hadn't meant to leave that in there.
struct NavigationBarModifier: ViewModifier {
var backgroundColor: UIColor?
var titleColor: UIColor?
init(backgroundColor: Color, titleColor: UIColor?) {
self.backgroundColor = UIColor(backgroundColor)
let coloredAppearance = UINavigationBarAppearance()
coloredAppearance.configureWithTransparentBackground()
coloredAppearance.backgroundColor = .clear // The key is here. Change the actual bar to clear.
coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]
coloredAppearance.shadowColor = .clear
UINavigationBar.appearance().standardAppearance = coloredAppearance
UINavigationBar.appearance().compactAppearance = coloredAppearance
UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
UINavigationBar.appearance().tintColor = titleColor
}
func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
Color(self.backgroundColor ?? .clear)
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
extension View {
func navigationBarColor(backgroundColor: Color, titleColor: UIColor?) -> some View {
self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
}
}
struct FirstView: View {
#State private var selection: String? = nil
var body: some View {
NavigationView {
GeometryReader { _ in
VStack {
Text("This is the first view")
NavigationLink(destination: SecondView(), tag: "SecondView", selection: $selection) {
EmptyView()
}
Button(action: {
self.selection = "SecondView"
print("Go to second view")
}) {
Text("Go to second view")
}
}
.navigationTitle("First")
.navigationBarTitleDisplayMode(.inline)
.navigationBarColor(backgroundColor: .red, titleColor: .black)
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct SecondView: View {
#State private var selection: String? = nil
var body: some View {
VStack {
Text("This is the second view")
NavigationLink(destination: ThirdView(), tag: "ThirdView", selection: $selection) {
EmptyView()
}
Button(action: {
self.selection = "ThirdView"
print("Go to third view")
}) {
Text("Go to third view")
}
}
.navigationTitle("Second")
.navigationBarTitleDisplayMode(.inline)
.navigationBarColor(backgroundColor: .blue, titleColor: .black)
}
}
struct ThirdView: View {
var body: some View {
ScrollView {
ForEach(0..<50) { _ in
Text("This is the third view")
}
}
.navigationTitle("Third")
.navigationBarTitleDisplayMode(.inline)
.navigationBarColor(backgroundColor: .green, titleColor: .black)
}
}
iOS 16
Since this version of SwiftUI, there is a dedicated modifier for setting any toolbar background color (including the navigation bar):
Xcode 14 beta 5 (Not working 🤦🏻‍♂️, waiting for beta 6...)
.toolbarBackground(.red, for: .navigationBar)
Xcode 14 beta 1,2,3,4
.toolbarBackground(.red, in: .navigationBar)
It works perfectly in in inline mode and also animates between modes.
For my custom view the following code worked well.
struct HomeView: View {
init() {
//Use this if NavigationBarTitle is with Large Font
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.systemIndigo]
//Use this if NavigationBarTitle is with displayMode = .inline
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.systemIndigo]
UINavigationBar.appearance().backgroundColor = UIColor.clear
UINavigationBar.appearance().barTintColor = UIColor(Color(red: 32 / 255, green: 72 / 255, blue: 63 / 255))
}
var body: some View {
NavigationView {
ZStack {
...
...
...
}
.padding(.zero)
.navigationTitle("Feedbacks")
}
}
}
and result is like that:
Here is a bit hacky solution, but it works for me (as of iOS 15) both for .large and .inline display modes.
import SwiftUI
enum Kind: String, CaseIterable {
case checking
case savings
case investment
}
struct PaddedList: View {
#Binding var name: String
#Binding var kind: Kind
var body: some View {
NavigationView {
List {
TextField("Account name", text: $name)
Picker("Kind", selection: $kind) {
ForEach(Kind.allCases, id: \.self) { kind in
Text(kind.rawValue).tag(kind)
}
}
.listRowSeparatorTint(.red)
Spacer()
}
.padding(.top, 1) // note top 1 padding!
.background(.green) // the color "bleeds" through
.navigationBarTitle("Navigation Bar")
}
}
}
struct PaddedList_Previews: PreviewProvider {
static var previews: some View {
PaddedList(name: .constant(""), kind: .constant(.checking))
}
}

SwiftUI 2.0 - TabView tab bar colors don't respect the current color scheme (dark or light mode)

I'm desperately trying to have my tab bar colors respect the current color scheme.
When the app is launched, the Colors are correct. But if I toggle dark and light mode, the colors don't switch back to the correct ones. The light mode colors are always applied. The code is available below the images (simplified for the demo).
Colors are specified in the Assets.xcassets catalog (Any / Light / Dark).
import SwiftUI
struct TabBarColorTest: View {
#Environment(\.colorScheme) var colorScheme
init() {
UITabBar.appearance().isTranslucent = true
UITabBar.appearance().tintColor = UIColor(named: "TabBarTint")
UITabBar.appearance().unselectedItemTintColor = UIColor(named: "TabBarUnselected")
UITabBar.appearance().barTintColor = UIColor(named: "TabBar")
UITabBar.appearance().backgroundColor = UIColor(named: "TabBar")
}
var body: some View {
TabView {
Text("Zero")
.tabItem {
Label("Zero", systemImage: "0.square.fill")
}
Text("One")
.tabItem {
Label("One", systemImage: "1.square.fill")
}
}
.onChange(of: colorScheme, perform: { value in
UITabBar.appearance().isTranslucent = true
UITabBar.appearance().tintColor = UIColor(named: "TabBarTint")
UITabBar.appearance().unselectedItemTintColor = UIColor(named: "TabBarUnselected")
UITabBar.appearance().barTintColor = UIColor(named: "TabBar")
UITabBar.appearance().backgroundColor = UIColor(named: "TabBar")
})
}
}
struct TabBarColorTest_Previews: PreviewProvider {
static var previews: some View {
TabBarColorTest()
}
}
By having the tab item tint color as a SwiftUI modifier and simplifying the initialization of the UIKIt configuration for the tab bar, the issue should be fixed. Tested on Xcode 12.4 with iOS 14 as a minimum target.
struct ContentView: View {
init() {
UITabBar.appearance().barTintColor = .systemBackground
UITabBar.appearance().unselectedItemTintColor = UIColor(named: "TabBarUnselected")
}
var body: some View {
TabView {
Text("Zero")
.tabItem {
Label("Zero", systemImage: "0.square.fill")
}
Text("One")
.tabItem {
Label("One", systemImage: "1.square.fill")
}
}
.accentColor(Color("TabBarTint"))
}
}

Change Tabbed View Bar Color SwiftUI

Does anyone know how to change the background colour of a tabbed view bottom bar?
I have set the accent colour which changed the colour of my icons when I select each tab bar item.
I have tried setting the background to a colour but it doesn't change the back, and tried setting background to an image just to be sure but that also doesn't do anything.
Wondering if I need to specifically access the bottom bar somehow and then set a property on that?
Here is a solution. You can change appearance of the UITabBar and change the TabBar.
struct TabView: View {
init() {
UITabBar.appearance().backgroundColor = UIColor.blue
}
var body: some View {
return TabbedView {
Text("This is tab 1").tag(0).tabItemLabel(Text("tab1"))
Text("This is tab 2").tag(1).tabItemLabel(Text("tab2"))
Text("This is tab 3").tag(2).tabItemLabel(Text("tab3"))
}
}
}
SwiftUI 1.0 - Using named colors
Combining barTintColor and isTranslucent
For some reason I wasn't getting the full color of my named color when I used just barTintColor or even backgroundColor. I had to include isTranslucent too.
Here is my named color:
Setting Just barTintColor
(As you can see, it is slightly faded)
Setting Just backgroundColor
(This darkens the bar a little bit)
Setting barTintColor & isTranslucent to False
This combination is what did it for me:
UITabBar.appearance().isTranslucent = false
UITabBar.appearance().barTintColor = UIColor(named: "Secondary")
In the init() add UITabBar.appearance().barTintColor = UIColor.blue
struct ContentView: View {
#State private var selection = 1
init() {
UITabBar.appearance().barTintColor = UIColor.blue
}
var body: some View {
TabView (selection:$selection){
Text("The First Tab")
.tabItem {
Image(systemName: "1.square.fill")
Text("First")
}
.tag(1)
Text("Another Tab")
.tabItem {
Image(systemName: "2.square.fill")
Text("Second")
}.tag(2)
Text("The Last Tab")
.tabItem {
Image(systemName: "3.square.fill")
Text("Third")
}.tag(3)
}
.accentColor(.white)
}
}
This one looks like a working solution based on the latest version of Swift and SwiftUI
struct TabBar: View {
init() {
UITabBar.appearance().barTintColor = UIcolor.black
var body: some View {
TabView {
HomeView().tabItem {
Image(systemName: "house.fill")
Text("Home")
}
MapView().tabItem {
Image(systemName: "mappin.circle.fill")
Text("Map")
}
}
.edgesIgnoringSafeArea(.top)
}
}
where HomeView() and MapView() are just some other views created earlier that will be displayed on tap.
It is important to set the colors for UITabBar before the TabView is shown. If not using a custom view with initializer, then you must make sure it is called before the TabView is loaded, for instance in the AppDelegate (when using the "UIKit App Delegate" in the project life cycle or otherwise adding it for "SwiftUI App" life cycle).
Then you can configure it with a UITabBarAppearance() object, for instance like so:
let tabBarAppeareance = UITabBarAppearance()
tabBarAppeareance.shadowColor = .gray // For line separator of the tab bar
tabBarAppeareance.backgroundColor = .black // For background color
UITabBar.appearance().standardAppearance = tabBarAppeareance
TabbedView has been deprecated, for now you can try:
struct AppTabbedView: View {
#State private var selection = 3
init() {
UITabBar.appearance().backgroundColor = UIColor.blue
}
var body: some View {
TabView (selection:$selection){
Text("The First Tab")
.tabItem {
Image(systemName: "1.square.fill")
Text("First")
}
.tag(1)
Text("Another Tab")
.tabItem {
Image(systemName: "2.square.fill")
Text("Second")
}.tag(2)
Text("The Last Tab")
.tabItem {
Image(systemName: "3.square.fill")
Text("Third")
}.tag(3)
}
.font(.headline)
}
}
In case if you need change background of unselected item and top line as well then you can stuck. Next is what will work for me. We will start from this one:
In first iteration I change everything except top line:
struct ContentView: View {
#ObservedObject var model: ContentViewModel
init(model: ContentViewModel) {
self.model = model
UITabBar.appearance().isTranslucent = false
UITabBar.appearance().unselectedItemTintColor = UIColor(Color.primary)
UITabBar.appearance().barTintColor = UIColor(Color("tab_background"))
}
var body: some View {
NavigationView {
TabView(selection: $model.selectedTab) {...}
}
}
}
But after that, I realize that I can't change the color of this line in the same way. So I will use #atineoSE answer. But realize that set the UITabBar.appearance().standardAppearance will totally override my previous customization. So I need to change it - here is the final code and result:
init(model: ContentViewModel) {
self.model = model
let itemAppearance = UITabBarItemAppearance()
itemAppearance.normal.iconColor = UIColor(Color.primary)
let appeareance = UITabBarAppearance()
appeareance.shadowColor = UIColor(Color("tab_separator"))
appeareance.backgroundColor = UIColor(Color("tab_background"))
appeareance.stackedLayoutAppearance = itemAppearance
appeareance.inlineLayoutAppearance = itemAppearance
appeareance.compactInlineLayoutAppearance = itemAppearance
UITabBar.appearance().standardAppearance = appeareance
}
Its Work for me in latest Versions
var body: some View {
TabView{
Text("Zain ahmed")
.font(.system(size: 30, weight: .bold, design: .rounded))
.tabItem {
Label("Home", systemImage: "house.fill")
}
Text("Bookmark Tab")
.font(.system(size: 30, weight: .bold, design: .rounded))
.tabItem {
Label("Bookmark", systemImage: "bookmark.circle.fill")
}
}
.onAppear() {
UITabBar.appearance().backgroundColor = .lightGray
}
}
init() {
UITabBar.appearance().barTintColor = .white
UITabBar.appearance().backgroundColor = .white
}
While this is great for light mode, when you switch to dark mode, the background for the tabbar stays the color you have selected. Any way to make the bar go to black when dark mode is sl