Dynamically set SwiftUI NavigationBarItems? - swiftui

How can you dynamically change SwiftUI Navigation Bar Items?
I have a TabView within a NavigationView, and I would like the Navigation Bar Items to change depending on tab that is selected. However, I am having a hard time determining how to change this with .onAppear(), assuming that is even what you are suppose to do.
My code is currently laid out as follows:
var body: some View {
NavigationView {
TabView {
contentWithNavigationButtons()
.tabItem {
Image(systemName: "house")
Text("Buttons")
}
contentWithoutNavigationButtons()
.tabItem {
Image(systemName: "person")
Text("No Buttons")
}
.onAppear {
//Navigation Bar Items should be removed
}
}
.navigationBarItems(trailing: someButton)
}

Here is a demo of possible solution - add tracking selection for tabs and make button depending of tab selection. Tested with Xcode 12 / iOS 14
struct DemoView: View {
#State private var selection = 0 // << here !!
var body: some View {
NavigationView {
TabView(selection: $selection) {
contentWithNavigationButtons()
.tabItem {
Image(systemName: "house")
Text("Buttons")
}.tag(0) // << here !!
contentWithoutNavigationButtons()
.tabItem {
Image(systemName: "person")
Text("No Buttons")
}.tag(1)
}
.navigationBarItems(trailing: Group {
if selection == 0 { // << here !!
Button("Some"){}
}
})
}
}
}

Related

Nav bar with toolbar buttons on a specific tabview item in swift

I have a TabView with three views (triangle, square and circle) nested inside a navigation view and link. TabView works fine. I'd like to have toolbar buttons for only a specific tabview; say circle. The toolbar modifier adds the buttons on all the tabviews.
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink() {
TabView {
Text("triangle")
.tabItem {
Label("triangle", systemImage: "triangle")
}
Text("square")
.tabItem {
Label("square", systemImage: "square")
}
Text("circle")
.tabItem {
Label("circle", systemImage: "circle")
}
}
.navigationTitle("Tabs")
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button("About") {
print("About tapped!")
}
Button("Help") {
print("Help tapped!")
}
}
}
} label: {
Text("Hello!")
}
.navigationTitle("Title")
}
}
}
How can I set this up to only show toolbar buttons on one tabview only?
I suppose a secondary option (way less preferred) may be to disable the buttons on tabviews where they are not needed (if possible).
It can be done with a selection state for TabView and making visibility of specific toolbar buttons depending on that state.
Here is a demo. Tested with Xcode 13.4 / iOS 15.5
struct ContentView: View {
#State private var selection = 0 // << here !!
var body: some View {
NavigationView {
NavigationLink() {
TabView(selection: $selection) { // << here !!
Text("triangle")
.tabItem {
Label("triangle", systemImage: "triangle")
}.tag(0)
Text("square")
.tabItem {
Label("square", systemImage: "square")
}.tag(1)
Text("circle")
.tabItem {
Label("circle", systemImage: "circle")
}.tag(2)
}
.navigationTitle("Tabs")
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if selection == 2 { // << here !!
Button("About") {
print("About tapped!")
}
Button("Help") {
print("Help tapped!")
}
}
}
}
} label: {
Text("Hello!")
}
.navigationTitle("Title")
}
}
}
Test code in GitHub

Closing A View From Another View

I am still learning SwiftUI and I have come across a small problem.
In my app, I have a main view. On the top is a search bar and at the bottom, a menu with different buttons. I want to change views when clicking those buttons. However, I only want to change the middle section.
No big deal, I will just put the middle part into a NavigationView. That works alright and I am able to change my views. My problem is that the buttons below do not have any impact on the new view.
To try to simplify: Let’s say I’m on home page. I then click the grocery list button (guess what I’m making school projects lol). My navigation link works just fine and goes to the list. So, now I’m on view 2 let’s say. When I press the home button, it doesn’t close that view and go to my main one. Here is my code setup:
import SwiftUI
struct ContentView: View {
#State private var searchText: String = ""
#State private var action: Int? = 0
var body: some View {
ZStack {
// Top Menu
VStack{
HStack {
Spacer()
TextField("Search",
text: $searchText)
.background(Color.white)
Button(action: {
self.action = 1
}, label: {
Image(systemName: "magnifyingglass.circle")
.font(.largeTitle)
})
Spacer()
}
// Body
NavigationView {
VStack {
Text("Can I See Something")
NavigationLink(destination: SearchView(), tag: 1, selection: $action) {
}
Text("Yes/No")
}
}
Spacer()
// Bottom Menu
HStack (alignment: .top) {
Spacer()
VStack {
Button(action: {
}, label: {
Image(systemName: "house.fill")
.font(.largeTitle)
})
.padding(.top)
Text("Home")
}
Divider()
.padding(.horizontal)
.frame(width: 2.5, height: 100)
VStack {
Button(action: {
}, label: {
Image(systemName: "newspaper")
.font(.largeTitle)
})
.padding(.top)
Text("Weekly\nAd")
.multilineTextAlignment(.center)
}
Divider()
.padding(.horizontal)
.frame(width: 2.5, height: 100)
VStack {
Button(action: {
}, label: {
Image(systemName: "checklist")
.font(.largeTitle)
})
.padding(.top)
Text("Grocery\nList")
.multilineTextAlignment(.center)
}
Divider()
.padding(.horizontal)
.frame(width: 2.5, height: 100)
VStack {
Button(action: {
}, label: {
Image(systemName: "person.crop.circle")
.font(.largeTitle)
})
.padding(.top)
Text("Account")
}
Spacer()
}
}
}
}
}
struct SearchView: View {
var body: some View {
ZStack {
Text("Nothing to see here!")
}
.navigationBarBackButtonHidden(true)
}
}
SearchView is a separate view (in its own file) in the app that opens up when the magnifying glass button is pressed. Currently it does not do anything. However I want to be able to press those buttons on this view above to still navigate the app.
Also, on another note, is there anyway to get rid of the back button?
In your code the buttons do not have any function.
Instead of creating a tab bar on your own, I'd rather take something like:
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
MainView()
.tabItem {
Label("Home", systemImage: "house.fill")
}
NewsView()
.tabItem {
Label("Weekly\nAd", systemImage: "newspaper")
}
OrderView()
.tabItem {
Label("Grocery\nList", systemImage: "checklist")
}
AccountView()
.tabItem {
Label("Account", systemImage: "person.crop.circle")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct MainView: View {
var body: some View {
Text("Home View")
}
}
struct NewsView: View {
var body: some View {
Text("News View")
}
}
struct OrderView: View {
var body: some View {
Text("Order View")
}
}
struct AccountView: View {
var body: some View {
Text("Account View")
}
}
In that case you'll have to create a view for each tab you are configuring (see the last 4 structs).
If you want to do it with a Stack with your own created buttons, I think you should create al 4 views as well and then you either hide them or put them out of focus by using an offset. In that case the buttons should hide/show the specific views or change the offset accordingly to move the specific views into the visible area. With the offset you also can add some animation.
Regarding the search bar on top of your app, since the views are all different, I wouldn't keep the same search bar everywhere, but if you really want to have it that way, you can embed the code + your search bar into a VStack (as you did it in your example).

SwiftUI TabView brightness views vertical location

I'm trying to change the brightness of a TabView in SwiftUI, but whenever the brightness toggles, the sub-views change their vertical position. This is highly mysterious to me, as it seems strange for brightness to have any influence at all on the position of views.
If you've been following my past few questions, you might recognize that I want to change the brightness because I want to dim the background view as a new view slides up (on the press of a button). That's why, in the sample code, we must include the Z-Stack.
Sample Code:
struct ContentView: View {
#State var press: Bool = Bool()
var body: some View {
ZStack {
TabView {
NavigationView {
Button(action: { press.toggle() }) {
Text("Toggle")
}
}
.tabItem {
Image(systemName: "square.stack").font(.title)
Text("View One")
}
NavigationView {
Button(action: { press.toggle() }) {
Text("Toggle")
}
}
.tabItem {
Image(systemName: "checkmark.square")
Text("View Two")
}
}
.brightness(press ? -0.1: 0)
}
}
}
The issue is with the multiple NavigationViews that are inside the TabView You really are supposed to have only 1 NavigationView at the root of the view hierarchy. Using multiple NavigationViews is discouraged and can lead to unexpected results, like this. Therefore, the inside of the body should be:
NavigationView {
ZStack {
TabView {
Button(action: { press.toggle() }) {
Text("Toggle")
}
.tabItem {
Image(systemName: "square.stack")
Text("View One")
}
Button(action: { press.toggle() }) {
Text("Toggle")
}
.tabItem {
Image(systemName: "checkmark.square")
Text("View Two")
}
}
.brightness(press ? -0.1: 0)
}
}

Navigation Link Returning Back Two Levels on Exit

I am having trouble with a return from a navigation view within a tabbed view. My project has a Settings tab where the user may select via navigation link "View Entries". And from there another navigation link to "Add New Entry". Returning from Add New Entry should bring you to View Entries but instead is return another level to the Setting Menu.
I am seeing a warning on the console stating "trying to pop to a missing destination at /Library/Caches/com.apple...". Using the tabbed view sample code at SwiftUI NavigationView trying to pop to missing destination (Monoceros?) I no longer get the "pop-to-missing-destination" warning but I still have the same problem with the navigation return.
The sample code below is ready to run and test in Xcode 12.
In the sample code below, tap settings and select the navigation view "View Entries". This would be a screen where entries are displayed in a list. Tapping the plus button is where new entries could be added. The textfield on the "Add New Entry" screen doesn't do anything. Clicking the Save or Back buttons should return you to "View Entries" screen but instead returns you to the Setting Menu. The Save button uses presentationMode.wrappedValue.dismiss to dismiss the view.
The fact that two different version of the tab view logic didn't have any impact on my navigation view return logic leads me to believe that I just have some kind on plain old bug in my navigation view logic but I sure don't see one. The sample code below is using the standard tab view logic.
struct ContentView: View {
#State private var selection = 0
var body: some View {
NavigationView {
TabView (selection: $selection) {
HomeView()
.tabItem {
Label("Home", systemImage: "house")
}.tag(1)
AView()
.tabItem {
Label("A", systemImage: "a.circle")
}.tag(2)
BView()
.tabItem {
Label("B", systemImage: "b.circle")
}.tag(3)
SettingsView()
.tabItem {
Label("Settings", systemImage: "gearshape")
}.tag(4)
}
}
}
}
struct HomeView: View {
var body: some View {
Text("Home Screen")
}
}
struct AView: View {
var body: some View {
Text("A Screen")
}
}
struct BView: View {
var body: some View {
Text("B Screen")
}
}
struct SettingsView: View {
var body: some View {
VStack (alignment: .leading) {
List {
Text("Settings")
.font(.title)
.fontWeight(.bold)
.padding(.leading, 15)
NavigationLink(destination: SetAView()) {Text("View Entries")}
}
}
.font(.body)
}
}
struct SetAView: View {
var body: some View {
List {
Text("View Entries")
.padding(.vertical, 10)
Text("Normally entires would be displayed here")
Text("Should return here upon adding new entry")
.padding(.vertical, 10)
Text("Click the + button to add new entry")
}
.navigationBarItems(trailing: NavigationLink (destination: AddTestView()) {
Image(systemName: "plus")
.resizable()
.foregroundColor(Color(.systemBlue))
.frame(width: 18, height: 18)
} // body
)
}
}
struct AddTestView: View {
#Environment(\.presentationMode) var presentationMode
#State private var catSelect: String = ""
var body: some View {
NavigationView {
VStack {
Form {
Section {
TextField("Enter Entry Name", text: $catSelect)
.padding(.horizontal, 20)
.keyboardType(.default)
}
}
}
.navigationBarTitle(Text("Add new Entry"), displayMode: .inline)
.navigationViewStyle(StackNavigationViewStyle())
.navigationBarItems(trailing: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text ("Save")
})
}
}
}
After considerable analysis I discovered in my actual code that I had two copies of NavigationView––nothing wrong with the TabView code. Removing the one NavigationView not in contentView then caused several functions from working so rebuilt them from scratch. Now have everything working with TabView and NaigationView including the back buttons.

How do I hide navigation bar in the tab bar's specific view in SwiftUI?

XCode11 beta3,
MacOS Catalina 10.15 Beta(19A501i)
I want to hide tabBar when push~ Any command will very helpful, Thanks~
Click me to show gif image
:
struct ContentView : View {
var body: some View {
WhenNavigationViewIsRootView()
}
}
struct WhenNavigationViewIsRootView : View {
var body: some View {
NavigationView {
TabbedView{
Rectangle().foregroundColor(.green)
.tag(0).tabItem{Text("Page1")}
VStack {
List {
ForEach(0...2) { i in
NavigationLink(
destination: Text("\(i)"),
label: {Text("\(i)")})
}
}
}.tag(1).tabItem{Text("Page2")}
}
.navigationBarHidden(true)
}
}
}
If you want to hide the navigation bar in a TabbedView, you have to set .navigationBarHidden(true) on the views nested inside TabbedView. This isn't enough, however. For whatever reason, SwiftUI requires that you first set the navigation bar title before you can hide the navigation bar.
NavigationView {
TabbedView{
Rectangle()
.foregroundColor(.green)
.tag(0)
.tabItem{
Text("Page1")
}
.navigationBarTitle("")
.navigationBarHidden(true)
List(0...2) { i in
NavigationLink(destination: Text("\(i)")) {
Text("\(i)")
}
}
.tag(1)
.tabItem {
Text("Page2")
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}