struct Conte111ntView: View {
#State private var selection: String? = nil
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Second View : click go to ThirdView ") .navigationBarTitle("Navigation").navigationBarHidden(true).gesture(TapGesture().onEnded{ v in
self.selection = "Third"
}), tag: "Second", selection: $selection) { EmptyView() }.isDetailLink(true)
NavigationLink(destination: Text("Third View : click go to SecondView ") .navigationBarTitle("Navigation").navigationBarHidden(true).gesture(TapGesture().onEnded{ v in
self.selection = "Second"
}), tag: "Third", selection: $selection) { EmptyView() }.isDetailLink(true)
Button("Tap to show second") {
self.selection = "Second"
}
Button("Tap to show third") {
self.selection = "Third"
}
}
.navigationBarTitle("Navigation").navigationBarHidden(true)
}
}
}
struct test_Previews: PreviewProvider {
static var previews: some View {
Conte111ntView()
}
}
I want to Second View -> Third View
but swiftUi behavior is: Second View -> rootView -> Third View
And quick tap in 'click go to ThirdView' And ,'Third View'
it get the wrong behavior 。 return to rootView
how can fix this
Or am I doing it the wrong way?
The following is a simpler version.
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: SecondView()) {
Text("Second View : click go to ThirdView")
}
Spacer()
NavigationLink(destination: ThirdView()) {
Text("Third View : click go to SecondView")
}
}
}
.navigationBarHidden(false)
}
}
struct SecondView: View {
var body: some View {
Text("SecondView is here!")
}
}
struct ThirdView: View {
var body: some View {
Text("ThirdView is here!")
}
}
Related
I am new to SwiftUI and have run into a little challenge. Whenever I go from my Home view to a sub-view and then back to the Home view, I am seeing extra space created in the Navigation view (see linked GIF). I was wondering if anyone had any advice - thanks in advance!
Here is the Home Screen:
struct Home: View {
#State private var view2 = false
var body: some View {
NavigationView {
VStack {
Text("Home View!")
.padding()
NavigationLink(destination: View2(), isActive: $view2) { }
Button {
self.view2 = true
} label: {
Text("Go to next view")
}
}
.navigationTitle("Home")
}
} }
Here is the sub-new (View2):
struct View2: View {
#State private var home = false
var body: some View {
VStack {
Text("This is View 2")
.padding()
NavigationLink(destination: Home().navigationBarBackButtonHidden(true), isActive: $home) { }
Button {
self.home = true
} label: {
Text("Go to Home view")
}
}
.navigationTitle("View 1")
} }
Link to GIF:
Visual GIF of the issue
Every time you push a new Home via a NavigationLink, you're adding another NavigationView to the hierarchy, since Home has a NavigationView in it.
To avoid that, you could separate the NavigationView out and instead link to View:
struct Home: View {
var body: some View {
NavigationView {
View1() //<-- Here
}
}
}
struct View1 : View {
#State private var view2 = false
var body: some View {
VStack {
Text("Home View!")
.padding()
NavigationLink(destination: View2(), isActive: $view2) { }
Button {
self.view2 = true
} label: {
Text("Go to next view")
}
}
.navigationTitle("Home")
}
}
struct View2: View {
#State private var home = false
var body: some View {
VStack {
Text("This is View 2")
.padding()
NavigationLink(destination: View1() //<-- Here
.navigationBarBackButtonHidden(true), isActive: $home) { }
Button {
self.home = true
} label: {
Text("Go to Home view")
}
}
.navigationTitle("View 2")
}
}
That being said, I'm a little skeptical of the strategy here. It seems like instead of pushing a new View1, you might just want to be going back to the existing one. In that case, your code could just look like this:
struct Home: View {
var body: some View {
NavigationView {
View1()
}
}
}
struct View1 : View {
#State private var view2 = false
var body: some View {
VStack {
Text("Home View!")
.padding()
NavigationLink(destination: View2(), isActive: $view2) { }
Button {
self.view2 = true
} label: {
Text("Go to next view")
}
}
.navigationTitle("Home")
}
}
struct View2: View {
#Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
Text("This is View 2")
.padding()
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Text("Go to Home view")
}
}
.navigationTitle("View 2")
}
}
I am trying to present a modal sheet upon selecting the menu item in the navigation bar. But, the sheet is not displayed. Upon debugging I noticed that the state variable showSheet is not getting updated and I am sort of lost as to why it is not updating.
Any help is very much appreciated. Thank you!
There is another post (#State not updating in SwiftUI 2) that has a similar issue. Is this a bug in SwiftUI?
Below is a full sample
I have a fileprivate enum that defines two cases for the views - add and edit
fileprivate enum SheetView {
case add, edit
}
Below is the ContentView. The ContentView declares two #State variables that are set based on the menu item selected
The menu items (var actionItems) are on the NavigationView and has menu with 2 buttons - Add and Edit. Each button has an action set to toggle the showSheetView and the showSheet variables. The content is presented based on which item is selected. Content is built using #ViewBuilder
struct ContentView: View {
#State private var showSheetView = false
#State private var showSheet: SheetView? = nil
var body: some View {
GeometryReader { g in
NavigationView {
Text("Main Page")
.padding()
.navigationBarTitle("Main Page")
.navigationBarItems(trailing: actionItems)
}
}.sheet(isPresented: $showSheetView) {
content
}
}
var actionItems: some View {
Menu {
Button(action: {
showSheet = .add
showSheetView.toggle()
}) {
Label("Add Asset", systemImage: "plus")
}
Button(action: {
showSheet = .edit
showSheetView.toggle()
}) {
Label("Edit Asset", systemImage: "minus")
}
} label: {
Image(systemName: "dot.circle.and.cursorarrow").resizable()
}
}
#ViewBuilder
var content: some View {
if let currentView = showSheet {
switch currentView {
case .add:
AddAsset(showSheetView: $showSheetView)
case .edit:
EditAsset(showSheetView: $showSheetView)
}
}
}
}
Below are the two Views - AddAsset and EditAsset
struct AddAsset: View {
#Binding var showSheetView: Bool
var body: some View {
NavigationView {
Text("Add Asset")
.navigationBarTitle(Text("Add"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheetView = false
}) {
Text("Done").bold()
})
}
}
}
struct EditAsset: View {
#Binding var showSheetView: Bool
var body: some View {
NavigationView {
Text("Edit Asset")
.navigationBarTitle(Text("Edit"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheetView = false
}) {
Text("Done").bold()
})
}
}
}
The solution is to use sheet(item: variant.
Here is fixed code (there are many changes so all components included). Tested with Xcode 12.1 / iOS 14.1
enum SheetView: Identifiable {
var id: Self { self }
case add, edit
}
struct ContentView: View {
#State private var showSheet: SheetView? = nil
var body: some View {
GeometryReader { g in
NavigationView {
Text("Main Page")
.padding()
.navigationBarTitle("Main Page")
.navigationBarItems(trailing: actionItems)
}
}.sheet(item: $showSheet) { mode in
content(for: mode)
}
}
var actionItems: some View {
Menu {
Button(action: {
showSheet = .add
}) {
Label("Add Asset", systemImage: "plus")
}
Button(action: {
showSheet = .edit
}) {
Label("Edit Asset", systemImage: "minus")
}
} label: {
Image(systemName: "dot.circle.and.cursorarrow").resizable()
}
}
#ViewBuilder
func content(for mode: SheetView) -> some View {
switch mode {
case .add:
AddAsset(showSheet: $showSheet)
case .edit:
EditAsset(showSheet: $showSheet)
}
}
}
struct AddAsset: View {
#Binding var showSheet: SheetView?
var body: some View {
NavigationView {
Text("Add Asset")
.navigationBarTitle(Text("Add"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheet = nil
}) {
Text("Done").bold()
})
}
}
}
struct EditAsset: View {
#Binding var showSheet: SheetView?
var body: some View {
NavigationView {
Text("Edit Asset")
.navigationBarTitle(Text("Edit"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
print("Dismissing sheet view...")
self.showSheet = nil
}) {
Text("Done").bold()
})
}
}
}
I've created a simple view acting as a navbar which contains a menu button and some text. I'm using this as a top-level element outside my NavigationView which allows me to have the view static across all child pages that come into view. The reason I'm trying not to use the default navbar, with navbar items, is to avoid the dismissal/creation that you get along with the fading animation when you switch views.
The problem I'm now facing is dismissing the child view's when I have navigated away from the parent view. I'm able to update the button from a menu icon to a back icon, but the action of the button is not triggered. Been looking online to see if anyone has done something similar but had no luck, I'm not sure what I'm trying to achieve is even possible or whether I am going about it the right way. Is there anyway to call self.presentationMode.wrappedValue.dismiss() from the child views even though the header is initialised in the root view? Any help is appreciated, here's what I have so far:
Root View (View1):
struct View1: View {
#State var showMenuButton: Bool = false
var body: some View {
VStack {
CustomNavigationView(showMenuButton: self.showMenuButton)
NavigationView {
NavigationLink(destination: View2()) {
Text("View 2")
}
.navigationBarTitle("")
.navigationBarHidden(true)
.onDisappear(){
self.showMenuButton = false
}
.onAppear() {
self.showMenuButton = true
}
}
}
}
}
Child View of root view (View2):
struct View2: View {
var body: some View {
VStack{
Text("This is View 2")
.navigationBarTitle("")
.navigationBarHidden(true)
NavigationLink(destination: View3()) {
Text("View 3")
}
}
}
}
Child view of view 2 (View3):
struct View3: View {
var body: some View {
VStack{
Text("This is View 3")
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
Custom Navigation View:
struct CustomNavigationView: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var showMenuButton = false
var body: some View {
VStack {
HStack {
if showMenuButton {
Button(action: {
//Do Something
}) {
Image(systemName: "line.horizontal.3")
.foregroundColor(.black)
}
} else {
Button(action: { self.presentationMode.wrappedValue.dismiss()}) {
Image(systemName: "arrow.left")
.foregroundColor(.black)
}
}
Text("Sometext")
}
}
}
}
The environment object 'presentationMode' that you used inside the first view cannot dismiss the views you pushed. Every view that wants to be dismissed must have their own objects. The object inside the first view does not belong to any other pushed views. So, you need to create view model to manage this task.
Here is the example code. Hope that will help you solve your problem.
class NavigationObserver: ObservableObject {
private var views: [Int:Binding<PresentationMode>] = [:]
private var current: Int = 0
func popView() {
guard let view = views[current] else {
return
}
view.wrappedValue.dismiss()
views[current] = nil
current -= 1
}
func pushView(id: Int, newView: Binding<PresentationMode>) {
guard views[id] == nil else {
return
}
current += 1
views[id] = newView
}
}
struct ContentView: View {
#State var showMenuButton: Bool = false
#ObservedObject var observer = NavigationObserver()
var body: some View {
VStack {
CustomNavigationView(observer: self.observer, showMenuButton: self.showMenuButton)
NavigationView {
NavigationLink(destination: View2(observer: self.observer)) {
Text("View 2")
}
.navigationBarTitle("")
.navigationBarHidden(true)
.onDisappear(){
self.showMenuButton = false
}
.onAppear() {
self.showMenuButton = true
}
}
}
}}
struct View2: View {
#Environment(\.presentationMode) var presentationMode
#ObservedObject var observer: NavigationObserver
var body: some View {
VStack{
Text("This is View 2")
.navigationBarTitle("")
.navigationBarHidden(true)
NavigationLink(destination: View3(observer: self.observer)) {
Text("View 3")
}
}.onAppear {
self.observer.pushView(id: 1, newView: self.presentationMode)
}
}}
struct View3: View {
#Environment(\.presentationMode) var presentationMode
#ObservedObject var observer: NavigationObserver
var body: some View {
VStack{
Text("This is View 3")
.navigationBarTitle("")
.navigationBarHidden(true)
}.onAppear
{
self.observer.pushView(id: 2, newView: self.presentationMode)
}
}
}
struct CustomNavigationView: View {
#ObservedObject var observer: NavigationObserver
var showMenuButton = false
var body: some View {
VStack {
HStack {
if showMenuButton {
Button(action: {
//Do Something
}) {
Image(systemName: "line.horizontal.3")
.foregroundColor(.black)
}
} else {
Button(action: {
self.observer.popView()
}) {
Image(systemName: "arrow.left")
.foregroundColor(.black)
}
}
Text("Sometext")
}
}
}
}
Thanks, X_X
Is it possible in SwiftUI to come back to a specific view? Let's say I have three views this way:
struct View1: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: View2()) {
Text("Navigate to View2")
}
.navigationBarTitle("View1")
}
}
}
}
struct View2: View {
var body: some View {
NavigationLink(destination: View3()) {
Text("Navigate to View3")
}
.navigationBarTitle("View2")
}
}
struct View3: View {
var body: some View {
Text("View3!")
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
View1()
}
}
#endif
The navigation works back and forth:
View1->View2->View3
View3->View2->View1
Is it possible to directly come back to View1 from the View3? What I'm looking for is something similar to the UIKit
func popToViewController(_ viewController: UIViewController,
animated: Bool) -> [UIViewController]?
Trying to solve this issue I ended up creating an open source project called swiftui-navigation-stack (https://github.com/biobeats/swiftui-navigation-stack). It contains the NavigationStackView, a view that mimics all the navigation behaviours of the standard NavigationView, adding some other features (all the features are explained in the readme of the repo). To answer the question here above we can use the NavigationStackView this way:
Let's pretend we have to implement a navigation like this:
View1 (push)-> View2 (push)-> View3 (push)-> View4 (pop)-> View2
First of all embed your first view in a NavigationStackView (as you'd do with the standard NavigationView):
struct RootView: View {
var body: some View {
NavigationStackView {
View1()
}
}
}
Let's create these simple views to build the example:
struct View1: View {
var body: some View {
ZStack {
Color.yellow.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 1")
Spacer()
PushView(destination: View2(), destinationId: "view2") {
Text("PUSH TO VIEW 2")
}
}
}
}
}
struct View2: View {
var body: some View {
ZStack {
Color.green.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 2")
Spacer()
PushView(destination: View3()) {
Text("PUSH TO VIEW 3")
}
}
}
}
}
struct View3: View {
var body: some View {
ZStack {
Color.gray.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 3")
Spacer()
PushView(destination: View4()) {
Text("PUSH TO VIEW 4")
}
}
}
}
}
struct View4: View {
var body: some View {
ZStack {
Color.white.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 4")
Spacer()
PopView(destination: .view(withId: "view2")) {
Text("POP TO VIEW 2")
}
}
}
}
}
PushView and PopView let you navigate between views and, among other things, they let you specify an identifier for a view (so that you can come back to it if you need).
The following is the complete example, you can copy-paste it to xCode to try it yourself:
import SwiftUI
import NavigationStack
struct RootView: View {
var body: some View {
NavigationStackView {
View1()
}
}
}
struct View1: View {
var body: some View {
ZStack {
Color.yellow.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 1")
Spacer()
PushView(destination: View2(), destinationId: "view2") {
Text("PUSH TO VIEW 2")
}
}
}
}
}
struct View2: View {
var body: some View {
ZStack {
Color.green.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 2")
Spacer()
PushView(destination: View3()) {
Text("PUSH TO VIEW 3")
}
}
}
}
}
struct View3: View {
var body: some View {
ZStack {
Color.gray.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 3")
Spacer()
PushView(destination: View4()) {
Text("PUSH TO VIEW 4")
}
}
}
}
}
struct View4: View {
var body: some View {
ZStack {
Color.white.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 4")
Spacer()
PopView(destination: .view(withId: "view2")) {
Text("POP TO VIEW 2")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
RootView()
}
}
The result is:
I can navigate to next screen by using NavigationButton (push) or present with PresentationButton (present) but i want to push when i tap on Buttton()
Button(action: {
// move to next screen
}) {
Text("See More")
}
is there a way to do it?
You can do using NavigationLink
Note: Please try in real device. in simulator sometimes not work properly.
struct MasterView: View {
#State var selection: Int? = nil
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailsView(), tag: 1, selection: $selection) {
Button("Press me") {
self.selection = 1
}
}
}
}
}
}
struct DetailsView: View {
#Environment(\.presentationMode) var presentation
var body: some View {
Group {
Button("Go Back") {
self.presentation.wrappedValue.dismiss()
}
}
}
}
As you can see to display the new view, add the NavigationLink with isActive: $pushView using <.hidden()> to hide the navigation "arrow".
Next add Text("See More") with tapGesture to make the text respond to taps. The variable pushView will change (false => true) when you click "See More" text.
import SwiftUI
struct ContentView: View {
#State var pushView = false
var body: some View {
NavigationView {
List {
HStack{
Text("test")
Spacer()
NavigationLink(destination: NewView(), isActive: $pushView) {
Text("")
}.hidden()
.navigationBarTitle(self.pushView ? "New view" : "default view")
Text("See More")
.padding(.trailing)
.foregroundColor(Color.blue)
.onTapGesture {
self.pushView.toggle()
}
}
}
}
}
}
struct NewView: View {
var body: some View {
Text("New View")
}
}
ContentView picture
NewView picture
To tap on button and navigate to next screen,You can use NavigationLink like below
NavigationView{
NavigationLink(destination: SecondView()) {
Text("Login")
.padding(.all, 5)
.frame(minWidth: 0, maxWidth: .infinity,maxHeight: 45, alignment: .center)
.foregroundColor(Color.white)
}
}
You can use NavigationLink to implement this:
struct DetailsView: View {
var body: some View {
VStack {
Text("Hello world")
}
}
}
struct ContentView: View {
#State var selection: Int? = nil
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailsView(), tag: 1, selection: $selection) {
Button("Press me") {
self.selection = 1
}
}
}
}
}
}