I decided to write a simple tab bar for macOS using Swift.
tabs.swift
import SwiftUI
import Foundation
import Combine
class ViewRouter: ObservableObject {
@Published var currentView = "home"
}
struct Tabs: View {
@ObservedObject var viewRouter = ViewRouter()
var body: some View {
GeometryReader { geometry in
VStack {
if self.viewRouter.currentView == "home" {
Text("Home")
} else if self.viewRouter.currentView == "settings" {
Text("Settings")
}
Spacer()
HStack {
{ () -> Text in
if self.viewRouter.currentView == "home" {
return Text("Home").foregroundColor(Color.blue)
} else {
return Text("Home")
}
}()
.onTapGesture {
self.viewRouter.currentView = "home"
}
{ () -> Text in
if self.viewRouter.currentView == "settings" {
return Text("Settings").foregroundColor(Color.blue)
} else {
return Text("Settings")
}
}()
.onTapGesture {
self.viewRouter.currentView = "settings"
}
}
}.edgesIgnoringSafeArea(.bottom).padding(20)
}
}
}
In ContentView.swift
, I just display this using Tabs()
in the ContentView
struct.
In the HStack
, I use two anonymous functions to give the text in the tab bar a blue color when that item is selected:
{ () -> Text in
if self.viewRouter.currentView == "home" {
return Text("Home").foregroundColor(Color.blue)
} else {
return Text("Home")
}
}()
.onTapGesture {
self.viewRouter.currentView = "home"
}
I also do this for the second item in the tab bar.
Is this the best (fastest and most concise) way to do this, or is there a better way?