How to dismiss a SwiftUI NavigationView from a parent view - ios

Usually, to implement a "custom dismiss button" within a SwiftUI NavigationView, I would use #Environment(\.dismiss) private var dismiss, and then call dismiss() to dismiss the view.
However, suppose I want to dismiss a NavigationLink from a parent of the NavigationView?
struct SwiftUIView: View {
var body: some View {
HStack {
Button(action: {
// dismiss view
}) {
Text("Dismiss View")
} // assume this button is always visible
NavigationView {
Text("This is the NavigationView")
NavigationLink {
Text("This is the view I want to exit")
} label: {
Text("Go to view I want to exit")
}
}
}
}
}
How would I go about dismissing the view displaying This is the view I want to exit, by clicking the Dismiss View button in the parent view?

Here is the solution:
struct SwiftUIView: View {
#State var isPresent = true
#State var isDismissed: Bool = false
var body: some View {
HStack {
Button(action: {
isDismissed = true
}) {
Text("Dismiss View")
} // assume this button is always visible
NavigationView {
VStack {
Text("This is the NavigationView")
NavigationLink {
ViewToDismiss(dismissView: $isDismissed)
} label: {
Text("Go to view I want to exit")
}
}
}
}
}
}
struct ViewToDismiss: View {
#Environment(\.dismiss) private var dismiss
#Binding var dismissView: Bool
var body: some View {
Text("This is the view I want to exit")
.onChange(of: dismissView,
perform:
( { newValue in
dismiss()
}))
}
}

Related

Why is NavigationLink not working inside of a SwiftUI alert?

I have an alert that upon tapping I would like to return the user back to another view. The alert is showing, but why does it not navigate upon tapping?
VStack{
.alert("End of available content", isPresented: $model.alertIsPresented) {
NavigationLink(destination: SearchView()) {
Button("OK", role:.cancel) {}
}
}
}
Because NavigationLink needs to be inside of a hierarchy using NavigationView. An alert is a modal presented outside of that structure.
If you would like to programmatically navigate, you can use the isActive property of a NavigationLink within the NavigationView hierarchy.
struct ContentView : View {
#State private var alertIsPresented = false
#State private var navLinkActive = false
var body: some View {
NavigationView {
VStack{
Button("Present alert") {
alertIsPresented = true
}
.alert("End of available content", isPresented: $alertIsPresented) {
Button("Navigate") {
navLinkActive = true
}
}
NavigationLink(isActive: $navLinkActive, destination: { SearchView() }, label: {
EmptyView()
})
}
}
}
}
struct SearchView : View {
var body: some View {
Text("Search")
}
}

SwiftUI Show navigation bar title on the back button but not in the previous View

I have two views, one leads to the other. I want that the second view uses the title of the first view for the back button, which should then be: "<View1".
I don't want to show the title in the first view.
Problem: I can't hide navigation bar because it will also hide a custom button which is within it. Setting .navigationTitle("") hides the title in the first view, but also hides it from the back button in the second view.
What I have now:
What I would like to have:
Code:
struct ContentView: View {
#State var isLinkActive = false
var body: some View {
NavigationView {
VStack {
NavigationLink("go to the second view", destination: SecondView(), isActive: $isLinkActive).navigationTitle("View1")
.navigationBarItems(leading: Button(action: {
()
}, label: {
Text("custom button")
}))
}
}.navigationViewStyle(StackNavigationViewStyle())
}
private func btnPressed() {
isLinkActive = true
}
}
struct SecondView: View {
var body: some View {
Color.blue
}
}
You need to create custom back button for destination view as well,and you shouldn’t set navigation title for navigationLink, that’s why you are not able to hide “View1” correctly.
Check below code.
import SwiftUI
struct Test: View {
#State var isLinkActive = false
var body: some View {
NavigationView {
VStack {
NavigationLink("go to the second view", destination: SecondView()
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button(action: {
isLinkActive = false
}, label: {
HStack{
Image(systemName: "backward.frame.fill")
Text("View1")
}
})) ,
isActive: $isLinkActive)
}.navigationBarItems(leading: Button(action: {
()
}, label: {
Text("custom button")
}))
}.navigationViewStyle(StackNavigationViewStyle())
}
private func btnPressed() {
isLinkActive = true
}
}
struct SecondView: View {
var body: some View {
Color.blue
}
}
You can try and make navigationBar code as reusable component, because you might need to do this at multiple places.
Output-:
I achieved this by using two modifiers on my main view. Similar to your case, I didn't want a title on the first view, but I wanted the back button on the pushed view to read < Home, not < Back.
.navigationTitle("Home")
.toolbar {
ToolbarItem(placement: .principal) {
Text("")
}
}

SwiftUI - How can I dismiss a view to root and then push a second view immediately afterwards?

Couldn't find anything relating to this issue in SwiftUI.
I have three views currently, RootView, DetailView1 and DetailView2. RootView will feature a button to push and show DetailView1, inside DetailView1 there will be a NavigationLink to dismiss DetailView1 to RootView and push DetailView2.
struct DetailView1: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
NavigationLink(destination: DetailView2()) {
Text("Tap to dismiss DetailView and show DetailView2")
.onTapGesture {
self.presentationMode.wrappedValue.dismiss()
}
}
}
}
}
struct DetailView2: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
Button(
"This is DetailView2",
action: { self.presentationMode.wrappedValue.dismiss() }
)
}
}
struct RootView: View {
var body: some View {
VStack {
NavigationLink(destination: DetailView1())
{ Text("This is root view. Tap to go to DetailView") }
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
RootView()
}
}
}
Expected behaviour:
User presses NavigationLink in DetailView1, the view is dismissed to RootView and DetailView2 is pushed up.
Current behaviour:
User presses NavigationLink in DetailView1, the view is dismissed to RootView, DetailView2 is not pushed.
You can do this by passing the active state of the second view. And change the #State value. It's a similar concept to the completion block in UIKit.
DetailView1
struct DetailView1: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#Binding var isActiveDetails2: Bool //<-- Here
var body: some View {
VStack {
Button("Tap to dismiss DetailView and show DetailView2") {
isActiveDetails2 = true //<-- Here
}
}
}
}
RootView
struct RootView: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#State private var isActiveDetails2: Bool = false
var body: some View {
VStack {
NavigationLink(destination: DetailView1(isActiveDetails2: $isActiveDetails2))
{ Text("This is root view. Tap to go to DetailView") }
NavigationLink(destination: DetailView2(), isActive: $isActiveDetails2) { //<-- Here
EmptyView()
}
}
}
}

onDisappear not called when a modal View is dismissed

I rely on the SwiftUI's .onDisappear to perform some logic but it is not being called when the user dismisses a modally presented view with the swipe gesture. To reproduce
Present a view modally a "ChildView 1"
On this view, push a "ChildView 2" as a navigation child
Swipe down to dismiss the modal view.
The .onDisappear of "ChildView 2" is not called.
Sample code to reproduce
import SwiftUI
struct ContentView: View {
#State var isShowingModal
var body: some View {
NavigationView {
Button(action: {
self.isShowingModal.toggle()
}) {
Text("Show Modal")
}
}
.sheet(isPresented: $isShowingModal) {
NavigationView {
ChildView(title: 1)
}
}
}
}
struct ChildView: View {
let title: Int
var body: some View {
NavigationLink(destination: ChildView(title: title + 1)) {
Text("Show Child")
}
.navigationBarTitle("View \(title)")
.onAppear {
print("onAppear ChildView \(self.title)")
}
.onDisappear {
print("onDisappear ChildView \(self.title)")
}
}
}
The output is:
onAppear ChildView 1
onAppear ChildView 2
onDisappear ChildView 1
If you're looking for logic to occur when the actual modal is dismissed, you're going to want to call that here, where I print out Modal Dismissed:
struct ContentView: View {
#State var isShowingModal = false
var body: some View {
NavigationView {
Button(action: {
self.isShowingModal.toggle()
}) {
Text("Show Modal")
}
}
.sheet(isPresented: $isShowingModal) {
NavigationView {
ChildView(title: 1)
}
.onDisappear {
print("Modal Dismissed")
}
}
}
}
struct ContentView: View {
#State var isShowingModal = false
var body: some View {
NavigationView {
Button(action: {
self.isShowingModal.toggle()
}) {
Text("Show Modal")
}
}
.sheet(isPresented: $isShowingModal) {
NavigationView {
ChildView(title: 1)
}
}
}
}
in this code, you have NavigationView, and when presenting sheet, you push there another NavigationView. This is the source of trouble
You don't need any NavigationView to present modals. If you like to present another modal from modal, you can use
import SwiftUI
struct ContentView: View {
var body: some View {
ChildView(title: 1)
}
}
struct ChildView: View {
#State var isShowingModal = false
let title: Int
var body: some View {
Button(action: {
self.isShowingModal.toggle()
}) {
Text("Show Modal \(title)").font(.largeTitle)
}
.sheet(isPresented: $isShowingModal) {
ChildView(title: self.title + 1)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
UPDATE
from Apple
Human Interface Guidelines
Modality is a design technique that presents content in a temporary mode that’s separate from the user's previous current context and requires an explicit action to exit

Dismiss a parent modal in SwiftUI from a NavigationView

I am aware of how to dismiss a modal from a child view using #Environment (\.presentationMode) var presentationMode / self.presentationMode.wrappedValue.dismiss() but this is a different issue.
When you present a multi-page NavigationView in a modal window, and have navigated through a couple of pages, the reference to presentationMode changes to be the NavigationView, so using self.presentationMode.wrappedValue.dismiss() simply pops the last NavigationView rather than dismissing the containing modal.
Is it possible - and if so how - to dismiss the containing modal from a page in a NavigationView tree?
Here's a simple example showing the problem. If you create an Xcode Single View app project using SwiftUI and replace the default ContentView code with this, it should work with no further changes.
import SwiftUI
struct ContentView: View {
#State var showModal: Bool = false
var body: some View {
Button(action: {
self.showModal.toggle()
}) {
Text("Launch Modal")
}
.sheet(isPresented: self.$showModal, onDismiss: {
self.showModal = false
}) {
PageOneContent()
}
}
}
struct PageOneContent: View {
var body: some View {
NavigationView {
VStack {
Text("I am Page One")
}
.navigationBarTitle("Page One")
.navigationBarItems(
trailing: NavigationLink(destination: PageTwoContent()) {
Text("Next")
})
}
}
}
struct PageTwoContent: View {
#Environment (\.presentationMode) var presentationMode
var body: some View {
NavigationView {
VStack {
Text("This should dismiss the modal. But it just pops the NavigationView")
.padding()
Button(action: {
// How to dismiss parent modal here instead
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Finish")
}
.padding()
.foregroundColor(.white)
.background(Color.blue)
}
.navigationBarTitle("Page Two")
}
}
}
Here is possible approach based on usage own explicitly created environment key (actually I have feeling that it is not correct to use presentationMode for this use-case.. anyway).
Proposed approach is generic and works from any view in modal view hierarchy. Tested & works with Xcode 11.2 / iOS 13.2.
// define env key to store our modal mode values
struct ModalModeKey: EnvironmentKey {
static let defaultValue = Binding<Bool>.constant(false) // < required
}
// define modalMode value
extension EnvironmentValues {
var modalMode: Binding<Bool> {
get {
return self[ModalModeKey.self]
}
set {
self[ModalModeKey.self] = newValue
}
}
}
struct ParentModalTest: View {
#State var showModal: Bool = false
var body: some View {
Button(action: {
self.showModal.toggle()
}) {
Text("Launch Modal")
}
.sheet(isPresented: self.$showModal, onDismiss: {
}) {
PageOneContent()
.environment(\.modalMode, self.$showModal) // < bind modalMode
}
}
}
struct PageOneContent: View {
var body: some View {
NavigationView {
VStack {
Text("I am Page One")
}
.navigationBarTitle("Page One")
.navigationBarItems(
trailing: NavigationLink(destination: PageTwoContent()) {
Text("Next")
})
}
}
}
struct PageTwoContent: View {
#Environment (\.modalMode) var modalMode // << extract modalMode
var body: some View {
NavigationView {
VStack {
Text("This should dismiss the modal. But it just pops the NavigationView")
.padding()
Button(action: {
self.modalMode.wrappedValue = false // << close modal
}) {
Text("Finish")
}
.padding()
.foregroundColor(.white)
.background(Color.blue)
}
.navigationBarTitle("Page Two")
}
}
}
Another Approach would be to simply use a notification for this case and just reset the triggering flag for your modal.
It is not the most beautiful solution for me but it is the solution I am most likely to still understand in a few months.
import SwiftUI
struct ContentView: View {
#State var showModalNav: Bool = false
var body: some View {
Text("Present Modal")
.padding()
.onTapGesture {
showModalNav.toggle()
}.sheet(isPresented: $showModalNav, content: {
ModalNavView()
}).onReceive(NotificationCenter.default.publisher(for: Notification.Name(rawValue: "PushedViewNotifciation"))) { _ in
showModalNav = false
}
}
}
struct ModalNavView: View {
var body: some View {
NavigationView {
NavigationLink(
destination: PushedView(),
label: {
Text("Show Another View")
}
)
}
}
}
struct PushedView: View {
var body: some View {
Text("Pushed View").onTapGesture {
NotificationCenter.default.post(Notification.init(name: Notification.Name(rawValue: "PushedViewNotifciation")))
}
}
}
If you don't want to loosely couple the views through a notification you could also just use a binding for this like so:
struct ContentView: View {
#State var showModalNav: Bool = false
var body: some View {
Text("Present Modal")
.padding()
.onTapGesture {
showModalNav.toggle()
}.sheet(isPresented: $showModalNav, content: {
ModalNavView(parentShowModal: $showModalNav)
}).onReceive(NotificationCenter.default.publisher(for: Notification.Name(rawValue: "PushedViewNotifciation"))) { _ in
showModalNav = false
}
}
}
struct ModalNavView: View {
#Binding var parentShowModal: Bool
var body: some View {
NavigationView {
NavigationLink(
destination: PushedView(parentShowModal: $parentShowModal),
label: {
Text("Show Another View")
}
)
}
}
}
struct PushedView: View {
#Binding var parentShowModal: Bool
var body: some View {
Text("Pushed View").onTapGesture {
parentShowModal = false
}
}
}
If it's only two levels, and especially if you can dismiss the sheet at multiple levels, you could include showModal as a binding variable in your navigation views below, and then toggling it anywhere would dismiss the entire sheet.
I would assume you could do something similar with showModal as an EnvironmentObject as Wei mentioned above - which might be better if there are more than two levels and you only want to dismiss the sheet at the most specific level.
I can't remember if there's some reason to move away from doing this as a binding variable, but it seems to be working for me.
import SwiftUI
struct ContentView: View {
#State var showModal: Bool = false
var body: some View {
Button(action: {
self.showModal.toggle()
}) {
Text("Launch Modal")
}
.sheet(isPresented: self.$showModal, onDismiss: {
self.showModal = false
}) {
// Bind showModal to the corresponding property in PageOneContent
PageOneContent(showModal: $showModal)
}
}
}
Then you add showModal as a binding variable in PageOneContent, and it is bound to the state variable in ContentView.
struct PageOneContent: View {
// add a binding showModal var in here
#Binding var showModal: Bool
var body: some View {
NavigationView {
VStack {
Text("I am Page One")
}
.navigationBarTitle("Page One")
.navigationBarItems(
// bind showModal again to PageTwoContent
trailing: NavigationLink(destination: PageTwoContent(showModal: $showModal)) {
Text("Next")
})
}
}
}
Finally, in PageTwoContent, you can add showModal here (and in the NavigationLink in PageOneContent, you have bound PageTwoContent's showModal to PageOneContent). Then in your button, all you have to do is toggle it, and it will dismiss the sheet.
struct PageTwoContent: View {
// Add showModal as a binding var here too.
#Binding var showModal: Bool
var body: some View {
NavigationView {
VStack {
Text("This should dismiss the modal. But it just pops the NavigationView")
.padding()
Button(action: {
// This will set the showModal var back to false in all three views, and will dismiss the current sheet.
self.showModal.toggle()
}) {
Text("Finish")
}
.padding()
.foregroundColor(.white)
.background(Color.blue)
}
.navigationBarTitle("Page Two")
}
}
}
I found out you can actually make showModal into an EnvironmentObject, then simplify toggle the showModal to false on PageTwoContent to dismiss both PageOneContent and PageTwoContent.

Resources