Navigationview Inside a Tabview Swift UI

NavigationView inside a TabView Swift UI

.tabItem should be used as a modifier on the view that represents that tab.

In the first example, this doesn't work because of a syntax error -- you're trying to use it on the opening of a closure in NavigationView {, when instead you want it on the outside of the closing brace: NavigationView { }.tabItem(...)

In the second example, you're using .tabItem as a modifier on the entire TabView instead of the NavigationView.

Both of your examples may have revealed what was going on more obviously if you indent your code so that you can see the hierarchy. Trying selecting your code in Xcode and using Ctrl-I to get Xcode to properly format it for you.

Here's a working version:

struct ContentView : View {
var body: some View {
TabView {
NavigationView {
Text("Tab bar test")
.navigationBarTitle("Page One")
}
.tabItem { //note how this is modifying `NavigationView`
Image(systemName: "1.circle")
Text("Home")
}

}
}
}

SwiftUI TabView inside a NavigationView

It is perfectly fine to have TabView() inside a NavigationView. Every time we switch between pages in any app, the navigating is mostly expected, so almost every view is inside the NavigtionView for this reason.

You can achieve this design with something like this (see the bottom images also):

struct LoginDemo: View {
@State var username = ""
var body: some View {
NavigationView {
VStack {
TextField("Enter your user name", text: $username)
.font(.headline)
.multilineTextAlignment(.center)
.frame(width: 300)
.border(.black)
NavigationLink {
GotoTabView()
} label: {
Text("search")
}
.disabled(username == "Admin" ? false : true)
}
}
.navigationTitle("Hey It's Nav View")
}
}
struct GotoTabView: View {
@State var temp = "status"
@State var selection = "view1"
var body: some View {
TabView(selection: $selection) {
Image("Swift")
.resizable()
.frame(width: 300, height: 300)
.tabItem {
Text("view 1")
}
.tag("view1")
Image("Swift")
.resizable()
.frame(width: 500, height: 500)
.tabItem {
Text("view 2")
}
.tag("view2")
}
.onChange(of: selection){ _ in
if selection == "view1" {
temp = "status"
}
else {
temp = "hero"
}
}
.toolbar{
ToolbarItem(placement: .principal) {
Text(temp)
}
}
}
}

NavigationView:

Sample Image

TabView:

Sample Image

Sample Image

SwiftUI navigation titles within TabView

We can define title depending on tab selection. Below is a simple demo of approach. Tested with Xcode 13 / iOS 15

struct ContentView: View {
@State var selection = 1

var body: some View {
NavigationView {
TabView(selection: $selection) {
Text("Hello")
.tabItem {
Image(systemName: "square.stack")
}.tag(1)
Text("Hello Again")
.tabItem {
Image(systemName: "checkmark.square")
}.tag(2)
}
.navigationTitle(selection == 1 ? "First" : "Second") // << here !!
}
}
}


Related Topics



Leave a reply



Submit