SwiftUI: Global Overlay That Can Be Triggered From Any View - swift

I'm quite new to the SwiftUI framework and I haven't wrapped my head around all of it yet so please bear with me.
Is there a way to trigger an "overlay view" from inside "another view" when its binding changes? See illustration below:
I figure this "overlay view" would wrap all my views. I'm not sure how to do this yet - maybe using ZIndex. I also guess I'd need some sort of callback when the binding changes, but I'm also not sure how to do that either.
This is what I've got so far:
ContentView
struct ContentView : View {
#State private var liked: Bool = false
var body: some View {
VStack {
LikeButton(liked: $liked)
}
}
}
LikeButton
struct LikeButton : View {
#Binding var liked: Bool
var body: some View {
Button(action: { self.toggleLiked() }) {
Image(systemName: liked ? "heart" : "heart.fill")
}
}
private func toggleLiked() {
self.liked = !self.liked
// NEED SOME SORT OF TOAST CALLBACK HERE
}
}
I feel like I need some sort of callback inside my LikeButton, but I'm not sure how this all works in Swift.
Any help with this would be appreciated. Thanks in advance!

It's quite easy - and entertaining - to build a "toast" in SwiftUI!
Let's do it!
struct Toast<Presenting>: View where Presenting: View {
/// The binding that decides the appropriate drawing in the body.
#Binding var isShowing: Bool
/// The view that will be "presenting" this toast
let presenting: () -> Presenting
/// The text to show
let text: Text
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .center) {
self.presenting()
.blur(radius: self.isShowing ? 1 : 0)
VStack {
self.text
}
.frame(width: geometry.size.width / 2,
height: geometry.size.height / 5)
.background(Color.secondary.colorInvert())
.foregroundColor(Color.primary)
.cornerRadius(20)
.transition(.slide)
.opacity(self.isShowing ? 1 : 0)
}
}
}
}
Explanation of the body:
GeometryReader gives us the preferred size of the superview , thus allowing the perfect sizing for our Toast.
ZStack stacks views on top of each other.
The logic is trivial: if the toast is not supposed to be seen (isShowing == false), then we render the presenting view. If the toast has to be presented (isShowing == true), then we render the presenting view with a little bit of blur - because we can - and we create our toast next.
The toast is just a VStack with a Text, with custom frame sizing, some design bells and whistles (colors and corner radius), and a default slide transition.
I added this method on View to make the Toast creation easier:
extension View {
func toast(isShowing: Binding<Bool>, text: Text) -> some View {
Toast(isShowing: isShowing,
presenting: { self },
text: text)
}
}
And a little demo on how to use it:
struct ContentView: View {
#State var showToast: Bool = false
var body: some View {
NavigationView {
List(0..<100) { item in
Text("\(item)")
}
.navigationBarTitle(Text("A List"), displayMode: .large)
.navigationBarItems(trailing: Button(action: {
withAnimation {
self.showToast.toggle()
}
}){
Text("Toggle toast")
})
}
.toast(isShowing: $showToast, text: Text("Hello toast!"))
}
}
I used a NavigationView to make sure the view fills the entire screen, so the Toast is sized and positioned correctly.
The withAnimation block ensures the Toast transition is applied.
How it looks:
It's easy to extend the Toast with the power of SwiftUI DSL.
The Text property can easily become a #ViewBuilder closure to accomodate the most extravagant of the layouts.
To add it to your content view:
struct ContentView : View {
#State private var liked: Bool = false
var body: some View {
VStack {
LikeButton(liked: $liked)
}
// make it bigger by using "frame" or wrapping it in "NavigationView"
.toast(isShowing: $liked, text: Text("Hello toast!"))
}
}
How to hide the toast afte 2 seconds (as requested):
Append this code after .transition(.slide) in the toast VStack.
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
withAnimation {
self.isShowing = false
}
}
}
Tested on Xcode 11.1

I modified Matteo Pacini's great answer, above, incorporating comments to have the Toast fade in and fade out after a delay. I also modified the View extension to be a bit more generic, and to accept a trailing closure similar to the way .sheet works.
ContentView.swift:
struct ContentView: View {
#State private var lightsOn: Bool = false
#State private var showToast: Bool = false
var body: some View {
VStack {
Button(action: {
if (!self.showToast) {
self.lightsOn.toggle()
withAnimation {
self.showToast = true
}
}
}){
Text("switch")
} //Button
.padding(.top)
Image(systemName: self.lightsOn ? "lightbulb" : "lightbulb.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.padding(.all)
.toast(isPresented: self.$showToast) {
HStack {
Text("Lights: \(self.lightsOn ? "ON" : "OFF")")
Image(systemName: self.lightsOn ? "lightbulb" : "lightbulb.fill")
} //HStack
} //toast
} //VStack
} //body
} //ContentView
View+Toast.swift:
extension View {
func toast<Content>(isPresented: Binding<Bool>, content: #escaping () -> Content) -> some View where Content: View {
Toast(
isPresented: isPresented,
presenter: { self },
content: content
)
}
}
Toast.swift:
struct Toast<Presenting, Content>: View where Presenting: View, Content: View {
#Binding var isPresented: Bool
let presenter: () -> Presenting
let content: () -> Content
let delay: TimeInterval = 2
var body: some View {
if self.isPresented {
DispatchQueue.main.asyncAfter(deadline: .now() + self.delay) {
withAnimation {
self.isPresented = false
}
}
}
return GeometryReader { geometry in
ZStack(alignment: .bottom) {
self.presenter()
ZStack {
Capsule()
.fill(Color.gray)
self.content()
} //ZStack (inner)
.frame(width: geometry.size.width / 1.25, height: geometry.size.height / 10)
.opacity(self.isPresented ? 1 : 0)
} //ZStack (outer)
.padding(.bottom)
} //GeometryReader
} //body
} //Toast
With this you could toast Text, or an Image (or both, as shown below), or any other View.

here is the how to overlay on all of your views including NavigationView!
create a class model to store your views!
class ParentView:ObservableObject {
#Published var view:AnyView = AnyView(EmptyView())
}
create the model in your parrent view and call it in your view hierarchy
pass this class to your environment object of your parent view
struct Example: View {
#StateObject var parentView = ParentView()
var body: some View {
ZStack{
NavigationView{
ChildView()
.environmentObject(parentView)
.navigationTitle("dynamic parent view")
}
parentView.view
}
}
}
from now on you can call parentview in your child view by
#EnvironmentObject var parentView:ParentView
then for example in your tap gesture, you can change the parent view and show a pop up that covers everything including your navigationviews
#StateObject var parentView = ParentView()
here is the full solution copy and play with it in your preview!
import SwiftUI
class ParentView:ObservableObject {
#Published var view:AnyView = AnyView(EmptyView())
}
struct example: View {
#StateObject var parentView = ParentView()
var body: some View {
ZStack{
NavigationView{
ChildView()
.environmentObject(parentView)
.navigationTitle("dynamic parent view")
}
parentView.view
}
}
}
struct ChildView: View {
#EnvironmentObject var parentView:ParentView
var body: some View {
ZStack{
Text("hello")
.onTapGesture {
parentView.view = AnyView(Color.red.opacity(0.4).ignoresSafeArea())
}
}
}
}
struct example_Previews: PreviewProvider {
static var previews: some View {
example()
}
}
also you can improve this dramatically like this...!
struct ParentViewModifire:ViewModifier {
#EnvironmentObject var parentView:ParentView
#Binding var presented:Bool
let anyView:AnyView
func body(content: Content) -> some View {
content
.onChange(of: presented, perform: { value in
if value {
parentView.view = anyView
}
})
}
}
extension View {
func overlayAll<Overlay>(_ overlay: Overlay, presented: Binding<Bool>) -> some View where Overlay : View {
self
.modifier(ParentViewModifire(presented: presented, anyView: AnyView(overlay)))
}
}
now in your child view you can call this modifier on your view
struct ChildView: View {
#State var newItemPopUp:Bool = false
var body: some View {
ZStack{
Text("hello")
.overlayAll(newCardPopup, presented: $newItemPopUp)
}
}
}

App-wide View
If you want it to be app-wide, put in somewhere app-wide! For example, you can add it to the MyProjectApp.swift (or in sceneDelegate for UIKit/AppDelegate projects) file like this:
Note that the button and the State are just for more explanation and you may consider changing them in the way you like
#main
struct SwiftUIAppPlaygroundApp: App { // <- Note that where we are!
#State var showToast = false
var body: some Scene {
WindowGroup {
Button("App-Wide Button") { showToast.toggle() }
ZStack {
ContentView() // <- The app flow
if showToast {
MyCustomToastView().ignoresSafeArea(.all, edges: .all) // <- App-wide overlays
}
}
}
}
}
See? now you can add any sort of view on anywhere of the screen, without blocking animations. Just convert that #State to some sort of AppState like Observables or Environments and boom! 💥 you did it!
Note that it is a demo, you should use an environment variable or smt to be able for changing it from outside of this view's body

Apple does not currently provide any APIs that allow you to make global views similar to their own alert pop-ups.
In fact these views are actually still using UIKit under the hood.
If you want your own global pop-ups you can sort of hack your own (note this isn't tested, but something very similar should work for global presentation of toasts):
import SwiftUI
import Foundation
/// Global class that will manage toasts
class ToastPresenter: ObservableObject {
// This static property probably isn't even needed as you can inject via #EnvironmentObject
static let shared: ToastPresenter = ToastPresenter()
private init() {}
#Published private(set) var isPresented: Bool = false
private(set) var text: String?
private var timer: Timer?
/// Call this function to present toasts
func presentToast(text: String, duration: TimeInterval = 5) {
// reset the toast if one is currently being presented.
isPresented = false
self.text = nil
timer?.invalidate()
self.text = text
isPresented = true
timer = Timer(timeInterval: duration, repeats: false) { [weak self] _ in
self?.isPresented = false
}
}
}
/// The UI for a toast
struct Toast: View {
var text: String
var body: some View {
Text(text)
.padding()
.background(Capsule().fill(Color.gray))
.shadow(radius: 6)
.transition(AnyTransition.opacity.animation(.default))
}
}
extension View {
/// ViewModifier that will present a toast when its binding changes
#ViewBuilder func toast(presented: Binding<Bool>, text: String) -> some View {
ZStack {
self
if presented.wrappedValue {
Toast(text: text)
}
}
.ignoresSafeArea(.all, edges: .all)
}
}
/// The first view in your app's view hierarchy
struct RootView: View {
#StateObject var toastPresenter = ToastPresenter.shared
var body: some View {
MyAppMainView()
.toast(presented: $toastPresenter.isPresented, text: toastPresenter.text)
// Inject the toast presenter into the view hierarchy
.environmentObject(toastPresenter)
}
}
/// Some view later on in the app
struct SomeViewDeepInTheHierarchy: View {
#EnvironmentObject var toastPresenter: ToastPresenter
var body: some View {
Button {
toastPresenter.presentToast(text: "Hello World")
} label: {
Text("Show Toast")
}
}
}

Use .presentation() to show an alert when the button is tapped.
In LikeButton:
#Binding var liked: Bool
var body: some View {
Button(action: {self.liked = !self.liked}, label: {
Image(systemName: liked ? "heart.fill" : "heart")
}).presentation($liked) { () -> Alert in
Alert.init(title: Text("Thanks for liking!"))
}
}
You can also use .presentation() to present other Modal views, like a Popover or ActionSheet. See here and the "See Also" section on that page in Apple's SwiftUI documentation for info on the different .presentation() options.
Edit: Example of what you want with a custom view using Popover:
#State var liked = false
let popover = Popover(content: Text("Thanks for liking!").frame(width: 200, height: 100).background(Color.white), dismissHandler: {})
var body: some View {
Button(action: {self.liked = !self.liked}, label: {
Image(systemName: liked ? "heart.fill" : "heart")
}).presentation(liked ? popover : nil)
}

I am using this open source: https://github.com/huynguyencong/ToastSwiftUI . It is very simple to use.
struct ContentView: View {
#State private var isShowingToast = false
var body: some View {
VStack(spacing: 20) {
Button("Show toast") {
self.isShowingToast = true
}
Spacer()
}
.padding()
// Just add a modifier to show a toast, with binding variable to control
.toast(isPresenting: $isShowingToast, dismissType: .after(3)) {
ToastView(message: "Hello world!", icon: .info)
}
}
}

Related

Tapping on a View to also change its sibling views

Within a VStack, I have 3 views. A view's selection and colour are toggled when tapping on them. I want the previously selected View to be deselected when selecting the next view.
The tapGesture is implemented in each view. I am not sure what is the best way to achieve this.
Thanks.
Here is the code sample:
struct ContentView: View {
#State var tile1 = Tile()
#State var tile2 = Tile()
#State var tile3 = Tile()
var body: some View {
VStack {
TileView(tile: tile1 )
TileView(tile: tile2 )
TileView(tile:tile3 )
}
.padding()
}
}
struct Tile: Identifiable, Equatable{
var id:UUID = UUID()
var isSelected:Bool = false
}
struct TileView: View {
#State var tile:Tile
var body: some View {
RoundedRectangle(cornerRadius: 15)
.fill( tile.isSelected ? Color.red : Color.yellow )
.frame(height: 100)
.padding()
.onTapGesture {
tile.isSelected.toggle()
}
}
}
You need to relate the 3 tiles somehow. An Array is an option. Then once they are related you can change the selection at that level.
extension Array where Element == Tile{
///Marks the passed `tile` as selected and deselects other tiles.
mutating func select(_ tile: Tile) {
for (idx, t) in self.enumerated(){
if t.id == tile.id{
self[idx].isSelected.toggle()
}else{
self[idx].isSelected = false
}
}
}
}
Then you can change your views to use the new function.
struct MyTileListView: View {
#State var tiles: [Tile] = [Tile(), Tile(), Tile()]
var body: some View {
VStack {
ForEach(tiles) { tile in
TileView(tile: tile, onSelect: {
//Use the array to select the tile
tiles.select(tile)
})
}
}
.padding()
}
}
struct TileView: View {
//#State just create a copy of the tile `#Binding` is a two-way connection if needed
let tile:Tile
///Called when the tile is selected
let onSelect: () -> Void
var body: some View {
RoundedRectangle(cornerRadius: 15)
.fill(tile.isSelected ? Color.red : Color.yellow)
.frame(height: 100)
.padding()
.onTapGesture {
onSelect()
}
}
}

How can I pop to the Root view using SwiftUI?

Finally now with Beta 5 we can programmatically pop to a parent View. However, there are several places in my app where a view has a "Save" button that concludes a several step process and returns to the beginning. In UIKit, I use popToRootViewController(), but I have been unable to figure out a way to do the same in SwiftUI.
Below is a simple example of the pattern I'm trying to achieve.
How can I do it?
import SwiftUI
struct DetailViewB: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("This is Detail View B.")
Button(action: { self.presentationMode.value.dismiss() } )
{ Text("Pop to Detail View A.") }
Button(action: { /* How to do equivalent to popToRootViewController() here?? */ } )
{ Text("Pop two levels to Master View.") }
}
}
}
struct DetailViewA: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("This is Detail View A.")
NavigationLink(destination: DetailViewB() )
{ Text("Push to Detail View B.") }
Button(action: { self.presentationMode.value.dismiss() } )
{ Text("Pop one level to Master.") }
}
}
}
struct MasterView: View {
var body: some View {
VStack {
Text("This is Master View.")
NavigationLink(destination: DetailViewA() )
{ Text("Push to Detail View A.") }
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
MasterView()
}
}
}
Setting the view modifier isDetailLink to false on a NavigationLink is the key to getting pop-to-root to work. isDetailLink is true by default and is adaptive to the containing View. On iPad landscape for example, a Split view is separated and isDetailLink ensures the destination view will be shown on the right-hand side. Setting isDetailLink to false consequently means that the destination view will always be pushed onto the navigation stack; thus can always be popped off.
Along with setting isDetailLink to false on NavigationLink, pass the isActive binding to each subsequent destination view. At last when you want to pop to the root view, set the value to false and it will automatically pop everything off:
import SwiftUI
struct ContentView: View {
#State var isActive : Bool = false
var body: some View {
NavigationView {
NavigationLink(
destination: ContentView2(rootIsActive: self.$isActive),
isActive: self.$isActive
) {
Text("Hello, World!")
}
.isDetailLink(false)
.navigationBarTitle("Root")
}
}
}
struct ContentView2: View {
#Binding var rootIsActive : Bool
var body: some View {
NavigationLink(destination: ContentView3(shouldPopToRootView: self.$rootIsActive)) {
Text("Hello, World #2!")
}
.isDetailLink(false)
.navigationBarTitle("Two")
}
}
struct ContentView3: View {
#Binding var shouldPopToRootView : Bool
var body: some View {
VStack {
Text("Hello, World #3!")
Button (action: { self.shouldPopToRootView = false } ){
Text("Pop to root")
}
}.navigationBarTitle("Three")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Definitely, malhal has the key to the solution, but for me, it is not practical to pass the Binding's into the View's as parameters. The environment is a much better way as pointed out by Imthath.
Here is another approach that is modeled after Apple's published dismiss() method to pop to the previous View.
Define an extension to the environment:
struct RootPresentationModeKey: EnvironmentKey {
static let defaultValue: Binding<RootPresentationMode> = .constant(RootPresentationMode())
}
extension EnvironmentValues {
var rootPresentationMode: Binding<RootPresentationMode> {
get { return self[RootPresentationModeKey.self] }
set { self[RootPresentationModeKey.self] = newValue }
}
}
typealias RootPresentationMode = Bool
extension RootPresentationMode {
public mutating func dismiss() {
self.toggle()
}
}
USAGE:
Add .environment(\.rootPresentationMode, self.$isPresented) to the root NavigationView, where isPresented is Bool used to present the first child view.
Either add .navigationViewStyle(StackNavigationViewStyle()) modifier to the root NavigationView, or add .isDetailLink(false) to the NavigationLink for the first child view.
Add #Environment(\.rootPresentationMode) private var rootPresentationMode to any child view from where pop to root should be performed.
Finally, invoking the self.rootPresentationMode.wrappedValue.dismiss() from that child view will pop to the root view.
I have published a complete working example on GitHub.
Since currently SwiftUI still uses a UINavigationController in the background it is also possible to call its popToRootViewController(animated:) function. You only have to search the view controller hierarchy for the UINavigationController like this:
struct NavigationUtil {
static func popToRootView() {
findNavigationController(viewController: UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController)?
.popToRootViewController(animated: true)
}
static func findNavigationController(viewController: UIViewController?) -> UINavigationController? {
guard let viewController = viewController else {
return nil
}
if let navigationController = viewController as? UINavigationController {
return navigationController
}
for childViewController in viewController.children {
return findNavigationController(viewController: childViewController)
}
return nil
}
}
And use it like this:
struct ContentView: View {
var body: some View {
NavigationView { DummyView(number: 1) }
}
}
struct DummyView: View {
let number: Int
var body: some View {
VStack(spacing: 10) {
Text("This is view \(number)")
NavigationLink(destination: DummyView(number: number + 1)) {
Text("Go to view \(number + 1)")
}
Button(action: { NavigationUtil.popToRootView() }) {
Text("Or go to root view!")
}
}
}
}
Introducing Apple's solution to this very problem
It also presented to you via HackingWithSwift (which I stole this from, LOL) under programmatic navigation:
(Tested on Xcode 12 and iOS 14)
Essentially, you use tag and selection inside navigationlink to go straight to whatever page you want.
struct ContentView: View {
#State private var selection: String? = nil
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Second View"), tag: "Second", selection: $selection) { EmptyView() }
NavigationLink(destination: Text("Third View"), tag: "Third", selection: $selection) { EmptyView() }
Button("Tap to show second") {
self.selection = "Second"
}
Button("Tap to show third") {
self.selection = "Third"
}
}
.navigationBarTitle("Navigation")
}
}
}
You can use an #environmentobject injected into ContentView() to handle the selection:
class NavigationHelper: ObservableObject {
#Published var selection: String? = nil
}
inject into App:
#main
struct YourApp: App {
var body: some Scene {
WindowGroup {
ContentView().environmentObject(NavigationHelper())
}
}
}
and use it:
struct ContentView: View {
#EnvironmentObject var navigationHelper: NavigationHelper
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Second View"), tag: "Second", selection: $navigationHelper.selection) { EmptyView() }
NavigationLink(destination: Text("Third View"), tag: "Third", selection: $navigationHelper.selection) { EmptyView() }
Button("Tap to show second") {
self.navigationHelper.selection = "Second"
}
Button("Tap to show third") {
self.navigationHelper.selection = "Third"
}
}
.navigationBarTitle("Navigation")
}
}
}
To go back to contentview in child navigationlinks, you just set the navigationHelper.selection = nil.
Note you don't even have to use tag and selection for subsequent child nav links if you don't want to—they will not have functionality to go to that specific navigationLink though.
As far as I can see, there isn't any easy way to do it with the current beta 5. The only way I found is very hacky, but it works.
Basically, add a publisher to your DetailViewA which will be triggered from DetailViewB. In DetailViewB dismiss the view and inform the publisher, which itself will close DetailViewA.
struct DetailViewB: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var publisher = PassthroughSubject<Void, Never>()
var body: some View {
VStack {
Text("This is Detail View B.")
Button(action: { self.presentationMode.value.dismiss() } )
{ Text("Pop to Detail View A.") }
Button(action: {
DispatchQueue.main.async {
self.presentationMode.wrappedValue.dismiss()
self.publisher.send()
}
} )
{ Text("Pop two levels to Master View.") }
}
}
}
struct DetailViewA: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var publisher = PassthroughSubject<Void, Never>()
var body: some View {
VStack {
Text("This is Detail View A.")
NavigationLink(destination: DetailViewB(publisher:self.publisher) )
{ Text("Push to Detail View B.") }
Button(action: { self.presentationMode.value.dismiss() } )
{ Text("Pop one level to Master.") }
}
.onReceive(publisher, perform: { _ in
DispatchQueue.main.async {
print("Go Back to Master")
self.presentationMode.wrappedValue.dismiss()
}
})
}
}
And Beta 6 still doesn't have a solution.
I found another way to go back to the root, but this time I'm losing the animation, and go straight to the root.
The idea is to force a refresh of the root view, this way leading to a cleaning of the navigation stack.
But ultimately only Apple could bring a proper solution, as the management of the navigation stack is not available in SwiftUI.
NB: The simple solution by notification below works on iOS, not watchOS, as watchOS clears the root view from memory after two navigation levels. But having an external class managing the state for watchOS should just work.
struct DetailViewB: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#State var fullDissmiss:Bool = false
var body: some View {
SGNavigationChildsView(fullDissmiss: self.fullDissmiss){
VStack {
Text("This is Detail View B.")
Button(action: { self.presentationMode.wrappedValue.dismiss() } )
{ Text("Pop to Detail View A.") }
Button(action: {
self.fullDissmiss = true
} )
{ Text("Pop two levels to Master View with SGGoToRoot.") }
}
}
}
}
struct DetailViewA: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#State var fullDissmiss:Bool = false
var body: some View {
SGNavigationChildsView(fullDissmiss: self.fullDissmiss){
VStack {
Text("This is Detail View A.")
NavigationLink(destination: DetailViewB() )
{ Text("Push to Detail View B.") }
Button(action: { self.presentationMode.wrappedValue.dismiss() } )
{ Text("Pop one level to Master.") }
Button(action: { self.fullDissmiss = true } )
{ Text("Pop one level to Master with SGGoToRoot.") }
}
}
}
}
struct MasterView: View {
var body: some View {
VStack {
Text("This is Master View.")
NavigationLink(destination: DetailViewA() )
{ Text("Push to Detail View A.") }
}
}
}
struct ContentView: View {
var body: some View {
SGRootNavigationView{
MasterView()
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
struct SGRootNavigationView<Content>: View where Content: View {
let cancellable = NotificationCenter.default.publisher(for: Notification.Name("SGGoToRoot"), object: nil)
let content: () -> Content
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
#State var goToRoot:Bool = false
var body: some View {
return
Group{
if goToRoot == false{
NavigationView {
content()
}
}else{
NavigationView {
content()
}
}
}.onReceive(cancellable, perform: {_ in
DispatchQueue.main.async {
self.goToRoot.toggle()
}
})
}
}
struct SGNavigationChildsView<Content>: View where Content: View {
let notification = Notification(name: Notification.Name("SGGoToRoot"))
var fullDissmiss:Bool{
get{ return false }
set{ if newValue {self.goToRoot()} }
}
let content: () -> Content
init(fullDissmiss:Bool, #ViewBuilder content: #escaping () -> Content) {
self.content = content
self.fullDissmiss = fullDissmiss
}
var body: some View {
return Group{
content()
}
}
func goToRoot(){
NotificationCenter.default.post(self.notification)
}
}
I figured out a simple solution to pop to the root view. I am sending a notification and then listening for the notification to change the id of the NavigationView; this will refresh the NavigationView. There is not an animation, but it looks good. Here is the example:
#main
struct SampleApp: App {
#State private var navigationId = UUID()
var body: some Scene {
WindowGroup {
NavigationView {
Screen1()
}
.id(navigationId)
.onReceive(NotificationCenter.default.publisher(for: Notification.Name("popToRootView"))) { output in
navigationId = UUID()
}
}
}
}
struct Screen1: View {
var body: some View {
VStack {
Text("This is screen 1")
NavigationLink("Show Screen 2", destination: Screen2())
}
}
}
struct Screen2: View {
var body: some View {
VStack {
Text("This is screen 2")
Button("Go to Home") {
NotificationCenter.default.post(name: Notification.Name("popToRootView"), object: nil)
}
}
}
}
I figured out how to use complex navigation in SwiftUI. The trick is to collect all the states of your views, which tell if they are shown.
Start by defining a NavigationController. I have added the selection for the tabview tab and the Boolean values saying if a specific view is shown:
import SwiftUI
final class NavigationController: ObservableObject {
#Published var selection: Int = 1
#Published var tab1Detail1IsShown = false
#Published var tab1Detail2IsShown = false
#Published var tab2Detail1IsShown = false
#Published var tab2Detail2IsShown = false
}
Setting up the tabview with two tabs and binding our NavigationController.selection to the tabview:
import SwiftUI
struct ContentView: View {
#EnvironmentObject var nav: NavigationController
var body: some View {
TabView(selection: self.$nav.selection) {
FirstMasterView()
.tabItem {
Text("First")
}
.tag(0)
SecondMasterView()
.tabItem {
Text("Second")
}
.tag(1)
}
}
}
As an example, this is one navigationStacks
import SwiftUI
struct FirstMasterView: View {
#EnvironmentObject var nav: NavigationController
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: FirstDetailView(), isActive: self.$nav.tab1Detail1IsShown) {
Text("go to first detail")
}
} .navigationBarTitle(Text("First MasterView"))
}
}
}
struct FirstDetailView: View {
#EnvironmentObject var nav: NavigationController
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack(spacing: 20) {
Text("first detail View").font(.title)
NavigationLink(destination: FirstTabLastView(), isActive: self.$nav.tab1Detail2IsShown) {
Text("go to last detail on nav stack")
}
Button(action: {
self.nav.tab2Detail1IsShown = false // true will go directly to detail
self.nav.tab2Detail2IsShown = false
self.nav.selection = 1
}) {
Text("Go to second tab")
}
}
// In case of collapsing all the way back
// there is a bug with the environment object
// to go all the way back I have to use the presentationMode
.onReceive(self.nav.$tab1Detail2IsShown, perform: { (out) in
if out == false {
self.presentationMode.wrappedValue.dismiss()
}
})
}
}
struct FirstTabLastView: View {
#EnvironmentObject var nav: NavigationController
var body: some View {
Button(action: {
self.nav.tab1Detail1IsShown = false
self.nav.tab1Detail2IsShown = false
}) {
Text("Done and go back to beginning of navigation stack")
}
}
}
This approach is quite SwiftUI-state oriented.
For me, in order to achieve full control for the navigation that is still missing in SwiftUI, I just embedded the SwiftUI View inside a UINavigationController. inside the SceneDelegate. Take note that I hide the navigation bar in order to use the NavigationView as my display.
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
UINavigationBar.appearance().tintColor = .black
let contentView = OnBoardingView()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
let hostingVC = UIHostingController(rootView: contentView)
let mainNavVC = UINavigationController(rootViewController: hostingVC)
mainNavVC.navigationBar.isHidden = true
window.rootViewController = mainNavVC
self.window = window
window.makeKeyAndVisible()
}
}
}
And then I have created this Protocol and Extension, HasRootNavigationController
import SwiftUI
import UIKit
protocol HasRootNavigationController {
var rootVC:UINavigationController? { get }
func push<Content:View>(view: Content, animated:Bool)
func setRootNavigation<Content:View>(views:[Content], animated:Bool)
func pop(animated: Bool)
func popToRoot(animated: Bool)
}
extension HasRootNavigationController where Self:View {
var rootVC:UINavigationController? {
guard let scene = UIApplication.shared.connectedScenes.first,
let sceneDelegate = scene as? UIWindowScene,
let rootvc = sceneDelegate.windows.first?.rootViewController
as? UINavigationController else { return nil }
return rootvc
}
func push<Content:View>(view: Content, animated:Bool = true) {
rootVC?.pushViewController(UIHostingController(rootView: view), animated: animated)
}
func setRootNavigation<Content:View>(views: [Content], animated:Bool = true) {
let controllers = views.compactMap { UIHostingController(rootView: $0) }
rootVC?.setViewControllers(controllers, animated: animated)
}
func pop(animated:Bool = true) {
rootVC?.popViewController(animated: animated)
}
func popToRoot(animated: Bool = true) {
rootVC?.popToRootViewController(animated: animated)
}
}
After that, on my SwiftUI View, I used/implemented the HasRootNavigationController protocol and extension
extension YouSwiftUIView:HasRootNavigationController {
func switchToMainScreen() {
self.setRootNavigation(views: [MainView()])
}
func pushToMainScreen() {
self.push(view: [MainView()])
}
func goBack() {
self.pop()
}
func showTheInitialView() {
self.popToRoot()
}
}
Here is the gist of my code in case I have some updates. https://gist.github.com/michaelhenry/945fc63da49e960953b72bbc567458e6
Thanks to Malhal's #Binding solution, I learned I was missing the .isDetailLink(false) modifier.
In my case, I don't want to use the #Binding at every subsequent view.
This is my solution where I am using EnvironmentObject.
Step 1: Create an AppState ObservableObject
import SwiftUI
import Combine
class AppState: ObservableObject {
#Published var moveToDashboard: Bool = false
}
Step 2: Create instance of AppState and add in contentView in SceneDelegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
let appState = AppState()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
contentView
.environmentObject(appState)
)
self.window = window
window.makeKeyAndVisible()
}
}
Step 3: Code of ContentView.swift
I am updating the appState value of the last view in the Stack which using .onReceive() I am capturing in the contentView to update the isActive to false for the NavigationLink.
The key here is to use .isDetailLink(false) with the NavigationLink. Otherwise, it will not work.
import SwiftUI
import Combine
class AppState: ObservableObject {
#Published var moveToDashboard: Bool = false
}
struct ContentView: View {
#EnvironmentObject var appState: AppState
#State var isView1Active: Bool = false
var body: some View {
NavigationView {
VStack {
Text("Content View")
.font(.headline)
NavigationLink(destination: View1(), isActive: $isView1Active) {
Text("View 1")
.font(.headline)
}
.isDetailLink(false)
}
.onReceive(self.appState.$moveToDashboard) { moveToDashboard in
if moveToDashboard {
print("Move to dashboard: \(moveToDashboard)")
self.isView1Active = false
self.appState.moveToDashboard = false
}
}
}
}
}
// MARK:- View 1
struct View1: View {
var body: some View {
VStack {
Text("View 1")
.font(.headline)
NavigationLink(destination: View2()) {
Text("View 2")
.font(.headline)
}
}
}
}
// MARK:- View 2
struct View2: View {
#EnvironmentObject var appState: AppState
var body: some View {
VStack {
Text("View 2")
.font(.headline)
Button(action: {
self.appState.moveToDashboard = true
}) {
Text("Move to Dashboard")
.font(.headline)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This solution is based on malhal's answer, uses suggestions from Imthath and Florin Odagiu, and required Paul Hudson's NavigationView video to bring it all together for me.
The idea is very simple. The isActive parameter of a navigationLink is set to true when tapped. That allows a second view to appear. You can use additional links to add more views. To go back to the root, just set isActive to false. The second view, plus any others that may have stacked up, disappear.
import SwiftUI
class Views: ObservableObject {
#Published var stacked = false
}
struct ContentView: View {
#ObservedObject var views = Views()
var body: some View {
NavigationView {
NavigationLink(destination: ContentView2(), isActive: self.$views.stacked) {
Text("Go to View 2") // Tapping this link sets stacked to true
}
.isDetailLink(false)
.navigationBarTitle("ContentView")
}
.environmentObject(views) // Inject a new views instance into the navigation view environment so that it's available to all views presented by the navigation view.
}
}
struct ContentView2: View {
var body: some View {
NavigationLink(destination: ContentView3()) {
Text("Go to View 3")
}
.isDetailLink(false)
.navigationBarTitle("View 2")
}
}
struct ContentView3: View {
#EnvironmentObject var views: Views
var body: some View {
Button("Pop to root") {
self.views.stacked = false // By setting this to false, the second view that was active is no more. Which means, the content view is being shown once again.
}
.navigationBarTitle("View 3")
}
}
IOS 16 Solution
Now finally you can pop to the root view with the newly added NavigationStack!!!
struct DataObject: Identifiable, Hashable {
let id = UUID()
let name: String
}
#available(iOS 16.0, *)
struct ContentView8: View {
#State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
Text("Root Pop")
.font(.largeTitle)
.foregroundColor(.primary)
NavigationLink("Click Item", value: DataObject.init(name: "Item"))
.listStyle(.plain)
.navigationDestination(for: DataObject.self) { course in
Text(course.name)
NavigationLink("Go Deeper", value: DataObject.init(name: "Item"))
Button("Back to root") {
path = NavigationPath()
}
}
}
.padding()
}
}
Here is my slow, animated, a bit rough backwards pop solution using onAppear, valid for Xcode 11 and iOS 13.1:
import SwiftUI
import Combine
struct NestedViewLevel3: View {
#Binding var resetView:Bool
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Spacer()
Text("Level 3")
Spacer()
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Back")
.padding(.horizontal, 15)
.padding(.vertical, 2)
.foregroundColor(Color.white)
.clipped(antialiased: true)
.background(
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color.blue)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 40, alignment: .center)
)}
Spacer()
Button(action: {
self.$resetView.wrappedValue = true
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Reset")
.padding(.horizontal, 15)
.padding(.vertical, 2)
.foregroundColor(Color.white)
.clipped(antialiased: true)
.background(
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color.blue)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 40, alignment: .center)
)}
Spacer()
}
.navigationBarBackButtonHidden(false)
.navigationBarTitle("Level 3", displayMode: .inline)
.onAppear(perform: {print("onAppear level 3")})
.onDisappear(perform: {print("onDisappear level 3")})
}
}
struct NestedViewLevel2: View {
#Binding var resetView:Bool
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Spacer()
NavigationLink(destination: NestedViewLevel3(resetView:$resetView)) {
Text("To level 3")
.padding(.horizontal, 15)
.padding(.vertical, 2)
.foregroundColor(Color.white)
.clipped(antialiased: true)
.background(
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color.gray)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 40, alignment: .center)
)
.shadow(radius: 10)
}
Spacer()
Text("Level 2")
Spacer()
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Back")
.padding(.horizontal, 15)
.padding(.vertical, 2)
.foregroundColor(Color.white)
.clipped(antialiased: true)
.background(
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color.blue)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 40, alignment: .center)
)}
Spacer()
}
.navigationBarBackButtonHidden(false)
.navigationBarTitle("Level 2", displayMode: .inline)
.onAppear(perform: {
print("onAppear level 2")
if self.$resetView.wrappedValue {
self.presentationMode.wrappedValue.dismiss()
}
})
.onDisappear(perform: {print("onDisappear level 2")})
}
}
struct NestedViewLevel1: View {
#Binding var resetView:Bool
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Spacer()
NavigationLink(destination: NestedViewLevel2(resetView:$resetView)) {
Text("To level 2")
.padding(.horizontal, 15)
.padding(.vertical, 2)
.foregroundColor(Color.white)
.clipped(antialiased: true)
.background(
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color.gray)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 40, alignment: .center)
)
.shadow(radius: 10)
}
Spacer()
Text("Level 1")
Spacer()
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Back")
.padding(.horizontal, 15)
.padding(.vertical, 2)
.foregroundColor(Color.white)
.clipped(antialiased: true)
.background(
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color.blue)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 40, alignment: .center)
)}
Spacer()
}
.navigationBarBackButtonHidden(false)
.navigationBarTitle("Level 1", displayMode: .inline)
.onAppear(perform: {
print("onAppear level 1")
if self.$resetView.wrappedValue {
self.presentationMode.wrappedValue.dismiss()
}
})
.onDisappear(perform: {print("onDisappear level 1")})
}
}
struct RootViewLevel0: View {
#Binding var resetView:Bool
var body: some View {
NavigationView {
VStack {
Spacer()
NavigationLink(destination: NestedViewLevel1(resetView:$resetView)) {
Text("To level 1")
.padding(.horizontal, 15)
.padding(.vertical, 2)
.foregroundColor(Color.white)
.clipped(antialiased: true)
.background(
RoundedRectangle(cornerRadius: 20)
.foregroundColor(Color.gray)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 40, alignment: .center)
)
.shadow(radius: 10)
}
//.disabled(false)
//.hidden()
Spacer()
}
}
//.frame(width:UIScreen.main.bounds.width,height: UIScreen.main.bounds.height - 110)
.navigationBarTitle("Root level 0", displayMode: .inline)
.navigationBarBackButtonHidden(false)
.navigationViewStyle(StackNavigationViewStyle())
.onAppear(perform: {
print("onAppear root level 0")
self.resetNavView()
})
.onDisappear(perform: {print("onDisappear root level 0")})
}
func resetNavView(){
print("resetting objects")
self.$resetView.wrappedValue = false
}
}
struct ContentView: View {
#State var resetView = false
var body: some View {
RootViewLevel0(resetView:$resetView)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Here is my solution. IT works anywhere, without dependency.
let window = UIApplication.shared.connectedScenes
.filter { $0.activationState == .foregroundActive }
.map { $0 as? UIWindowScene }
.compactMap { $0 }
.first?.windows
.filter { $0.isKeyWindow }
.first
let nvc = window?.rootViewController?.children.first as? UINavigationController
nvc?.popToRootViewController(animated: true)
NavigationViewKit
import NavigationViewKit
NavigationView {
List(0..<10) { _ in
NavigationLink("abc", destination: DetailView())
}
}
.navigationViewManager(for: "nv1", afterBackDo: {print("back to root") })
In any view in NavigationView:
#Environment(\.navigationManager) var nvmanager
Button("back to root view") {
nvmanager.wrappedValue.popToRoot(tag:"nv1") {
print("other back")
}
}
You can also call it through NotificationCenter without calling it in the view
let backToRootItem = NavigationViewManager.BackToRootItem(tag: "nv1", animated: false, action: {})
NotificationCenter.default.post(name: .NavigationViewManagerBackToRoot, object: backToRootItem)
Details
Xcode Version 13.2.1 (13C100), Swift 5.5
Solution
Linked list
https://github.com/raywenderlich/swift-algorithm-club/blob/master/Linked%20List/LinkedList.swift
NavigationStack
import SwiftUI
import Combine
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Custom NavigationLink
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
final class CustomNavigationLinkViewModel<CustomViewID>: ObservableObject where CustomViewID: Equatable {
private weak var navigationStack: NavigationStack<CustomViewID>?
/// `viewId` is used to find a `CustomNavigationLinkViewModel` in the `NavigationStack`
let viewId = UUID().uuidString
/// `customId` is used to mark a `CustomNavigationLink` in the `NavigationStack`. This is kind of external id.
/// In `NavigationStack` we always prefer to use `viewId`. But from time to time we need to implement `pop several views`
/// and that is the purpose of the `customId`
/// Developer can just create a link with `customId` e.g. `navigationStack.navigationLink(customId: "123") { .. }`
/// And to pop directly to view `"123"` should use `navigationStack.popToLast(customId: "123")`
let customId: CustomViewID?
#Published var isActive = false {
didSet { navigationStack?.updated(linkViewModel: self) }
}
init (navigationStack: NavigationStack<CustomViewID>, customId: CustomViewID? = nil) {
self.navigationStack = navigationStack
self.customId = customId
}
}
extension CustomNavigationLinkViewModel: Equatable {
static func == (lhs: CustomNavigationLinkViewModel, rhs: CustomNavigationLinkViewModel) -> Bool {
lhs.viewId == rhs.viewId && lhs.customId == rhs.customId
}
}
struct CustomNavigationLink<Label, Destination, CustomViewID>: View where Label: View, Destination: View, CustomViewID: Equatable {
/// Link `ViewModel` where all states are stored
#StateObject var viewModel: CustomNavigationLinkViewModel<CustomViewID>
let destination: () -> Destination
let label: () -> Label
var body: some View {
NavigationLink(isActive: $viewModel.isActive, destination: destination, label: label)
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: NavigationStack
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class NavigationStack<CustomViewID>: ObservableObject where CustomViewID: Equatable {
typealias Link = WeakReference<CustomNavigationLinkViewModel<CustomViewID>>
private var linkedList = LinkedList<Link>()
func navigationLink<Label, Destination>(customId: CustomViewID? = nil,
#ViewBuilder destination: #escaping () -> Destination,
#ViewBuilder label: #escaping () -> Label)
-> some View where Label: View, Destination: View {
createNavigationLink(customId: customId, destination: destination, label: label)
}
private func createNavigationLink<Label, Destination>(customId: CustomViewID? = nil,
#ViewBuilder destination: #escaping () -> Destination,
#ViewBuilder label: #escaping () -> Label)
-> CustomNavigationLink<Label, Destination, CustomViewID> where Label: View, Destination: View {
.init(viewModel: CustomNavigationLinkViewModel(navigationStack: self, customId: customId),
destination: destination,
label: label)
}
}
// MARK: Nested Types
extension NavigationStack {
/// To avoid retain cycle it is important to store weak reference to the `CustomNavigationLinkViewModel`
final class WeakReference<T> where T: AnyObject {
private(set) weak var weakReference: T?
init(value: T) { self.weakReference = value }
deinit { print("deinited WeakReference") }
}
}
// MARK: Searching
extension NavigationStack {
private func last(where condition: (Link) -> Bool) -> LinkedList<Link>.Node? {
var node = linkedList.last
while(node != nil) {
if let node = node, condition(node.value) {
return node
}
node = node?.previous
}
return nil
}
}
// MARK: Binding
extension NavigationStack {
fileprivate func updated(linkViewModel: CustomNavigationLinkViewModel<CustomViewID>) {
guard linkViewModel.isActive else {
switch linkedList.head?.value.weakReference {
case nil: break
case linkViewModel: linkedList.removeAll()
default:
last (where: { $0.weakReference === linkViewModel })?.previous?.next = nil
}
return
}
linkedList.append(WeakReference(value: linkViewModel))
}
}
// MARK: pop functionality
extension NavigationStack {
func popToRoot() {
linkedList.head?.value.weakReference?.isActive = false
}
func pop() {
linkedList.last?.value.weakReference?.isActive = false
}
func popToLast(customId: CustomViewID) {
last (where: { $0.weakReference?.customId == customId })?.value.weakReference?.isActive = false
}
}
#if DEBUG
extension NavigationStack {
var isEmpty: Bool { linkedList.isEmpty }
var count: Int { linkedList.count }
func testCreateNavigationLink<Label, Destination>(viewModel: CustomNavigationLinkViewModel<CustomViewID>,
#ViewBuilder destination: #escaping () -> Destination,
#ViewBuilder label: #escaping () -> Label)
-> CustomNavigationLink<Label, Destination, CustomViewID> where Label: View, Destination: View {
.init(viewModel: viewModel, destination: destination, label: label)
}
}
#endif
Usage (short sample)
Create NavigationLink:
struct Page: View {
#EnvironmentObject var navigationStack: NavigationStack<String>
var body: some View {
navigationStack.navigationLink {
NextView(...)
} label: {
Text("Next page")
}
}
}
Pop functionality
struct Page: View {
#EnvironmentObject var navigationStack: NavigationStack<String>
var body: some View {
Button("Pop") {
navigationStack.pop()
}
Button("Pop to Page 1") {
navigationStack.popToLast(customId: "1")
}
Button("Pop to root") {
navigationStack.popToRoot()
}
}
}
Usage (full sample)
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
addTab(title: "Tab 1", systemImageName: "house")
addTab(title: "Tab 2", systemImageName: "bookmark")
}
}
func addTab(title: String, systemImageName: String) -> some View {
NavigationView {
RootPage(title: "\(title) home")
.navigationBarTitle(title)
}
.environmentObject(NavigationStack<String>())
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: systemImageName)
Text(title)
}
}
}
struct RootPage: View {
let title: String
var body: some View {
SimplePage(title: title, pageCount: 0)
}
}
struct SimplePage: View {
#EnvironmentObject var navigationStack: NavigationStack<String>
var title: String
var pageCount: Int
var body: some View {
VStack {
navigationStack.navigationLink(customId: "\(pageCount)") {
// router.navigationLink {
SimplePage(title: "Page: \(pageCount + 1)", pageCount: pageCount + 1)
} label: {
Text("Next page")
}
Button("Pop") {
navigationStack.pop()
}
Button("Pop to Page 1") {
navigationStack.popToLast(customId: "1")
}
Button("Pop to root") {
navigationStack.popToRoot()
}
}
.navigationTitle(title)
}
}
Some Unit tests
#testable import SwiftUIPop
import XCTest
import SwiftUI
import Combine
class SwiftUIPopTests: XCTestCase {
typealias CustomLinkID = String
typealias Stack = NavigationStack<CustomLinkID>
private let stack = Stack()
}
// MARK: Empty Navigation Stack
extension SwiftUIPopTests {
func testNoCrashOnPopToRootOnEmptyStack() {
XCTAssertTrue(stack.isEmpty)
stack.popToRoot()
}
func testNoCrashOnPopToLastOnEmptyStack() {
XCTAssertTrue(stack.isEmpty)
stack.popToLast(customId: "123")
}
func testNoCrashOnPopOnEmptyStack() {
XCTAssertTrue(stack.isEmpty)
stack.pop()
}
}
// MARK: expectation functions
private extension SwiftUIPopTests {
func navigationStackShould(beEmpty: Bool) {
if beEmpty {
XCTAssertTrue(stack.isEmpty, "Navigation Stack should be empty")
} else {
XCTAssertFalse(stack.isEmpty, "Navigation Stack should not be empty")
}
}
}
// MARK: Data / model generators
private extension SwiftUIPopTests {
func createNavigationLink(viewModel: CustomNavigationLinkViewModel<CustomLinkID>, stack: Stack)
-> CustomNavigationLink<EmptyView, EmptyView, CustomLinkID> {
stack.testCreateNavigationLink(viewModel: viewModel) {
EmptyView()
} label: {
EmptyView()
}
}
func createNavigationLinkViewModel(customId: CustomLinkID? = nil) -> CustomNavigationLinkViewModel<CustomLinkID> {
.init(navigationStack: stack, customId: customId)
}
}
// MARK: test `isActive` changing from `true` to `false` on `pop`
extension SwiftUIPopTests {
private func isActiveChangeOnPop(customId: String? = nil,
popAction: (Stack) -> Void,
file: StaticString = #file,
line: UInt = #line) {
navigationStackShould(beEmpty: true)
let expec = expectation(description: "Wait for viewModel.isActive changing")
var canalables = Set<AnyCancellable>()
let viewModel = createNavigationLinkViewModel(customId: customId)
let navigationLink = createNavigationLink(viewModel: viewModel, stack: stack)
navigationLink.viewModel.isActive = true
navigationLink.viewModel.$isActive.dropFirst().sink { value in
expec.fulfill()
}.store(in: &canalables)
navigationStackShould(beEmpty: false)
popAction(stack)
waitForExpectations(timeout: 2)
navigationStackShould(beEmpty: true)
}
func testIsActiveChangeOnPop() {
isActiveChangeOnPop { $0.pop() }
}
func testIsActiveChangeOnPopToRoot() {
isActiveChangeOnPop { $0.popToRoot() }
}
func testIsActiveChangeOnPopToLast() {
let customId = "1234"
isActiveChangeOnPop(customId: customId) { $0.popToLast(customId: customId) }
}
func testIsActiveChangeOnPopToLast2() {
navigationStackShould(beEmpty: true)
let expec = expectation(description: "Wait")
var canalables = Set<AnyCancellable>()
let viewModel = createNavigationLinkViewModel(customId: "123")
let navigationLink = createNavigationLink(viewModel: viewModel, stack: stack)
navigationLink.viewModel.isActive = true
navigationLink.viewModel.$isActive.dropFirst().sink { value in
expec.fulfill()
}.store(in: &canalables)
navigationStackShould(beEmpty: false)
stack.popToLast(customId: "1234")
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
expec.fulfill()
}
waitForExpectations(timeout: 3)
navigationStackShould(beEmpty: false)
}
}
// MARK: Check that changing `CustomNavigationLinkViewModel.isActive` will update `Navigation Stack`
extension SwiftUIPopTests {
// Add and remove view to the empty stack
private func isActiveChangeUpdatesNavigationStack1(createLink: (Stack) -> CustomNavigationLink<EmptyView, EmptyView, String>) {
navigationStackShould(beEmpty: true)
let navigationLink = createLink(stack)
navigationStackShould(beEmpty: true)
navigationLink.viewModel.isActive = true
navigationStackShould(beEmpty: false)
navigationLink.viewModel.isActive = false
navigationStackShould(beEmpty: true)
}
func testIsActiveChangeUpdatesNavigationStack1() {
isActiveChangeUpdatesNavigationStack1 { stack in
let viewModel = createNavigationLinkViewModel()
return createNavigationLink(viewModel: viewModel, stack: stack)
}
}
func testIsActiveChangeUpdatesNavigationStack2() {
isActiveChangeUpdatesNavigationStack1 { stack in
let viewModel = createNavigationLinkViewModel(customId: "123")
return createNavigationLink(viewModel: viewModel, stack: stack)
}
}
// Add and remove view to the non-empty stack
private func isActiveChangeUpdatesNavigationStack2(createLink: (Stack) -> CustomNavigationLink<EmptyView, EmptyView, String>) {
navigationStackShould(beEmpty: true)
let viewModel1 = createNavigationLinkViewModel()
let navigationLink1 = createNavigationLink(viewModel: viewModel1, stack: stack)
navigationLink1.viewModel.isActive = true
navigationStackShould(beEmpty: false)
XCTAssertEqual(stack.count, 1, "Navigation Stack Should contains only one link")
let navigationLink2 = createLink(stack)
navigationLink2.viewModel.isActive = true
navigationStackShould(beEmpty: false)
navigationLink2.viewModel.isActive = false
XCTAssertEqual(stack.count, 1, "Navigation Stack Should contains only one link")
}
func testIsActiveChangeUpdatesNavigationStack3() {
isActiveChangeUpdatesNavigationStack2 { stack in
let viewModel = createNavigationLinkViewModel()
return createNavigationLink(viewModel: viewModel, stack: stack)
}
}
func testIsActiveChangeUpdatesNavigationStack4() {
isActiveChangeUpdatesNavigationStack2 { stack in
let viewModel = createNavigationLinkViewModel(customId: "123")
return createNavigationLink(viewModel: viewModel, stack: stack)
}
}
}
I recently created an open source project called swiftui-navigation-stack. It's an alternative navigation stack for SwiftUI. Take a look at the README for all the details; it's really easy to use.
First of all, if you want to navigate between screens (i.e., fullscreen views) define your own simple Screen view:
struct Screen<Content>: View where Content: View {
let myAppBackgroundColour = Color.white
let content: () -> Content
var body: some View {
ZStack {
myAppBackgroundColour.edgesIgnoringSafeArea(.all)
content()
}
}
}
Then embed your root in a NavigationStackView (as you'd do with the standard NavigationView):
struct RootView: View {
var body: some View {
NavigationStackView {
Homepage()
}
}
}
Now let's create a couple of child views just to show you the basic behaviour:
struct Homepage: View {
var body: some View {
Screen {
PushView(destination: FirstChild()) {
Text("PUSH FORWARD")
}
}
}
}
struct FirstChild: View {
var body: some View {
Screen {
VStack {
PopView {
Text("JUST POP")
}
PushView(destination: SecondChild()) {
Text("PUSH FORWARD")
}
}
}
}
}
struct SecondChild: View {
var body: some View {
Screen {
VStack {
PopView {
Text("JUST POP")
}
PopView(destination: .root) {
Text("POP TO ROOT")
}
}
}
}
}
You can exploit PushView and PopView to navigate back and forth. Of course, your content view inside the SceneDelegate must be:
// Create the SwiftUI view that provides the window contents.
let contentView = RootView()
The result is:
There is a simple solution in iOS 15 for that by using dismiss() and passing dismiss to the subview:
struct ContentView: View {
#State private var showingSheet = false
var body: some View {
NavigationView {
Button("show sheet", action: { showingSheet.toggle()})
.navigationTitle("ContentView")
}.sheet(isPresented: $showingSheet) { FirstSheetView() }
}
}
struct FirstSheetView: View {
#Environment(\.dismiss) var dismiss
var body: some View {
NavigationView {
List {
NavigationLink(destination: SecondSheetView(dismiss: _dismiss)) {
Text("show 2nd Sheet view")
}
NavigationLink(destination: ThirdSheetView(dismiss: _dismiss)) {
Text("show 3rd Sheet view")
}
Button("cancel", action: {dismiss()})
} .navigationTitle("1. SheetView")
}
}
}
struct SecondSheetView: View {
#Environment(\.dismiss) var dismiss
var body: some View {
List {
NavigationLink(destination: ThirdSheetView(dismiss: _dismiss)) {
Text("show 3rd SheetView")
}
Button("cancel", action: {dismiss()})
} .navigationTitle("2. SheetView")
}
}
struct ThirdSheetView: View {
#Environment(\.dismiss) var dismiss
var body: some View {
List {
Button("cancel", action: {dismiss()})
} .navigationTitle("3. SheetView")
}
}
I did not find a solution in SwiftUI yet, but I found the
library CleanUI.
Using the CUNavigation class, I can achieve exactly the navigation pattern I wanted.
An example from the library's README:
NavigationView {
Button(action: {
CUNavigation.pushToSwiftUiView(YOUR_VIEW_HERE)
}){
Text("Push To SwiftUI View")
}
Button(action: {
CUNavigation.popToRootView()
}){
Text("Pop to the Root View")
}
Button(action: {
CUNavigation.pushBottomSheet(YOUR_VIEW_HERE)
}){
Text("Push to a Botton-Sheet")
}
}
This is an update to x0randgat3's answer that works for multiple NavigationViews within a TabView.
struct NavigationUtil {
static func popToRootView() {
findNavigationController(viewController: UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController)?
.popToRootViewController(animated: true)
}
static func findNavigationController(viewController: UIViewController?) -> UINavigationController? {
guard let viewController = viewController else {
return nil
}
if let navigationController = viewController as? UITabBarController {
return findNavigationController(viewController: navigationController.selectedViewController)
}
if let navigationController = viewController as? UINavigationController {
return navigationController
}
for childViewController in viewController.children {
return findNavigationController(viewController: childViewController)
}
return nil
}
}
I came up with another technique which works but it still feels strange. It also still animates both screens dismissing, but it's a little cleaner. You can either A ) Pass a closure down to the subsequent detail screens or B ) pass detailB the presentationMode of detailA. Both of these require dismissing detailB, then delaying a short while so detailA is back on-screen before attempting to dismiss detailA.
let minDelay = TimeInterval(0.001)
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink("Push Detail A", destination: DetailViewA())
}.navigationBarTitle("Root View")
}
}
}
struct DetailViewA: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Spacer()
NavigationLink("Push Detail With Closure",
destination: DetailViewWithClosure(dismissParent: { self.dismiss() }))
Spacer()
NavigationLink("Push Detail with Parent Binding",
destination: DetailViewWithParentBinding(parentPresentationMode: self.presentationMode))
Spacer()
}.navigationBarTitle("Detail A")
}
func dismiss() {
print ("Detail View A dismissing self.")
presentationMode.wrappedValue.dismiss()
}
}
struct DetailViewWithClosure: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#State var dismissParent: () -> Void
var body: some View {
VStack {
Button("Pop Both Details") { self.popParent() }
}.navigationBarTitle("Detail With Closure")
}
func popParent() {
presentationMode.wrappedValue.dismiss()
DispatchQueue.main.asyncAfter(deadline: .now() + minDelay) { self.dismissParent() }
}
}
struct DetailViewWithParentBinding: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#Binding var parentPresentationMode: PresentationMode
var body: some View {
VStack {
Button("Pop Both Details") { self.popParent() }
}.navigationBarTitle("Detail With Binding")
}
func popParent() {
presentationMode.wrappedValue.dismiss()
DispatchQueue.main.asyncAfter(deadline: .now() + minDelay) { self.parentPresentationMode.dismiss() }
}
}
The more I think about how SwiftUI works and how things are structured, the less I think Apple will provide something equivalent to popToRootViewController or other direct edits to the navigation stack. It flies in the face of the way SwiftUI builds up view structs because it lets a child view reach up into a parent's state and manipulate it. Which is exactly what these approaches do, but they do it explicitly and overtly. DetailViewA can't create either of the of the destination views without providing access into its own state, meaning the author has to think through the implications of providing said access.
Elementary.
Enough in the root view (where you want to go back) use NavigationLink with an isActive designer. In the last view, switch to the FALSE variable controlling the isActive parameter.
In the Swift version 5.5 use .isDetaillink(false) is optional.
You can use some common class as I have in the example, or transmit this variable down the VIEW hierarchy through binding. Use how it is more convenient for you.
class ViewModel: ObservableObject {
#Published var isActivate = false
}
#main
struct TestPopToRootApp: App {
let vm = ViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(vm)
}
}
}
struct ContentView: View {
#EnvironmentObject var vm: ViewModel
var body: some View {
NavigationView {
NavigationLink("Go to view2", destination: NavView2(), isActive: $vm.isActivate)
.navigationTitle(Text("Root view"))
}
}
}
struct NavView2: View {
var body: some View {
NavigationLink("Go to view3", destination: NavView3())
.navigationTitle(Text("view2"))
}
}
struct NavView3: View {
#EnvironmentObject var vm: ViewModel
var body: some View {
Button {
vm.isActivate = false
} label: {
Text("Back to root")
}
.navigationTitle(Text("view3"))
}
}
To go to Root View without using .isDetailLink(false) you need to remove NavigationLink from hierarchy view of Root View
class NavigationLinkStore: ObservableObject {
static let shared = NavigationLinkStore()
#Published var showLink = false
}
struct NavigationLinkView: View {
#ObservedObject var store = NavigationLinkStore.shared
#State var isActive = false
var body: some View {
NavigationView {
VStack {
Text("Main")
Button("Go to View1") {
Task {
store.showLink = true
try await Task.sleep(seconds: 0.1)
isActive = true
}
}
if store.showLink {
NavigationLink(
isActive: $isActive,
destination: { NavigationLink1View() },
label: { EmptyView() }
)
}
}
}
}
}
struct NavigationLink1View: View {
var body: some View {
VStack {
Text("View1")
NavigationLink("Go to View 2", destination: NavigationLink2View())
}
}
}
struct NavigationLink2View: View {
#ObservedObject var store = NavigationLinkStore.shared
var body: some View {
VStack {
Text("View2")
Button("Go to root") {
store.showLink = false
}
}
}
}
Here's a generic approach for complex navigation which combines many approaches described here. This pattern is useful if you have many flows which need to pop back to the root and not just one.
First, set up your environment ObservableObject and for readability, use an enum to type your views.
class ActiveView : ObservableObject {
#Published var selection: AppView? = nil
}
enum AppView : Comparable {
case Main, Screen_11, Screen_12, Screen_21, Screen_22
}
[...]
let activeView = ActiveView()
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(activeView))
In your main ContentView, use buttons with NavigationLink on EmptyView(). We do that to use the isActive parameter of NavigationLink instead of the tag and selection. Screen_11 on main view needs to remain active on Screen_12, and conversely, Screen_21 needs to remain active with Screen_22 or otherwise the views will pop out. Don't forget to set your isDetailLink to false.
struct ContentView: View {
#EnvironmentObject private var activeView: ActiveView
var body: some View {
NavigationView {
VStack {
// These buttons navigate by setting the environment variable.
Button(action: { self.activeView.selection = AppView.Screen_1.1}) {
Text("Navigate to Screen 1.1")
}
Button(action: { self.activeView.selection = AppView.Screen_2.1}) {
Text("Navigate to Screen 2.1")
}
// These are the navigation link bound to empty views so invisible
NavigationLink(
destination: Screen_11(),
isActive: orBinding(b: self.$activeView.selection, value1: AppView.Screen_11, value2: AppView.Screen_12)) {
EmptyView()
}.isDetailLink(false)
NavigationLink(
destination: Screen_21(),
isActive: orBinding(b: self.$activeView.selection, value1: AppView.Screen_21, value2: AppView.Screen_22)) {
EmptyView()
}.isDetailLink(false)
}
}
}
You can use the same pattern on Screen_11 to navigate to Screen_12.
Now, the breakthrough for that complex navigation is the orBinding. It allows the stack of views on a navigation flow to remain active. Whether you are on Screen_11 or Screen_12, you need the NavigationLink(Screen_11) to remain active.
// This function create a new Binding<Bool> compatible with NavigationLink.isActive
func orBinding<T:Comparable>(b: Binding<T?>, value1: T, value2: T) -> Binding<Bool> {
return Binding<Bool>(
get: {
return (b.wrappedValue == value1) || (b.wrappedValue == value2)
},
set: { newValue in } // Don't care the set
)
}
I found a solution that works fine for me. Here is how it works:
A GIF image shows how it works
In the ContentView.swift file:
define a RootSelection class, declare an #EnvironmentObject of RootSelection to record the tag of the current active NavigationLink only in root view.
add a modifier .isDetailLink(false) to each NavigationLink that is not a final detail view.
use a file system hierarchy to simulate the NavigationView.
this solution works fine when the root view has multiple NavigationLink.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
SubView(folder: rootFolder)
}
}
}
struct SubView: View {
#EnvironmentObject var rootSelection: RootSelection
var folder: Folder
var body: some View {
List(self.folder.documents) { item in
if self.folder.documents.count == 0 {
Text("empty folder")
} else {
if self.folder.id == rootFolder.id {
NavigationLink(item.name, destination: SubView(folder: item as! Folder), tag: item.id, selection: self.$rootSelection.tag)
.isDetailLink(false)
} else {
NavigationLink(item.name, destination: SubView(folder: item as! Folder))
.isDetailLink(false)
}
}
}
.navigationBarTitle(self.folder.name, displayMode: .large)
.listStyle(SidebarListStyle())
.overlay(
Button(action: {
rootSelection.tag = nil
}, label: {
Text("back to root")
})
.disabled(self.folder.id == rootFolder.id)
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(RootSelection())
}
}
class RootSelection: ObservableObject {
#Published var tag: UUID? = nil
}
class Document: Identifiable {
let id = UUID()
var name: String
init(name: String) {
self.name = name
}
}
class File: Document {}
class Folder: Document {
var documents: [Document]
init(name: String, documents: [Document]) {
self.documents = documents
super.init(name: name)
}
}
let rootFolder = Folder(name: "root", documents: [
Folder(name: "folder1", documents: [
Folder(name: "folder1.1", documents: []),
Folder(name: "folder1.2", documents: []),
]),
Folder(name: "folder2", documents: [
Folder(name: "folder2.1", documents: []),
Folder(name: "folder2.2", documents: []),
])
])
.environmentObject(RootSelection()) is required for the ContentView() object in xxxApp.swift files.
import SwiftUI
#main
struct DraftApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(RootSelection())
}
}
}
malhal's answer is definitely the proper one.
I made a wrapper to NavigationLink that allows me to apply any modifiers I need besides the isDetailLink(false) one and capture whatever data I need.
Specifically, it captures the isActive binding or the tag binding so that I can reset those when I want to pop to whatever view declared itself the root.
Setting isRoot = true will store the binding for that view, and the dismiss parameter takes an optional closure in case you need something done when the pop happens.
I copied the basic signatures from the SwiftUI NavigationLinks initializers for simple boolean or tag based navigation so that it is easy to edit existing usages. It should be straightforward to add others if needed.
The wrapper looks like this:
struct NavigationStackLink<Label, Destination> : View where Label : View, Destination : View {
var isActive: Binding<Bool>? // Optionality implies whether tag or Bool binding is used
var isRoot: Bool = false
let link: NavigationLink<Label, Destination>
private var dismisser: () -> Void = {}
/// Wraps [NavigationLink](https://developer.apple.com/documentation/swiftui/navigationlink/init(isactive:destination:label:))
/// `init(isActive: Binding<Bool>, destination: () -> Destination, label: () -> Label)`
/// - Parameters:
/// - isActive: A Boolean binding controlling the presentation state of the destination
/// - isRoot: Indicate if this is the root view. Used to pop to root level. Default `false`
/// - dismiss: A closure that is called when the link destination is about to be dismissed
/// - destination: The link destination view
/// - label: The links label
init(isActive: Binding<Bool>, isRoot : Bool = false, dismiss: #escaping () -> Void = {}, #ViewBuilder destination: #escaping () -> Destination, #ViewBuilder label: #escaping () -> Label) {
self.isActive = isActive
self.isRoot = isRoot
self.link = NavigationLink(isActive: isActive, destination: destination, label: label)
self.dismisser = dismiss
}
/// Wraps [NavigationLink ](https://developer.apple.com/documentation/swiftui/navigationlink/init(tag:selection:destination:label:))
init<V>(tag: V, selection: Binding<V?>, isRoot : Bool = false, dismiss: #escaping () -> Void = {}, #ViewBuilder destination: #escaping () -> Destination, #ViewBuilder label: #escaping () -> Label) where V : Hashable
{
self.isRoot = isRoot
self.link = NavigationLink(tag: tag, selection: selection, destination: destination, label: label)
self.dismisser = dismiss
self.isActive = Binding (get: {
selection.wrappedValue == tag
}, set: { newValue in
if newValue {
selection.wrappedValue = tag
} else {
selection.wrappedValue = nil
}
})
}
// Make sure you inject your external store into your view hierarchy
#EnvironmentObject var viewRouter: ViewRouter
var body: some View {
// Store whatever you need to in your external object
if isRoot {
viewRouter.root = isActive
}
viewRouter.dismissals.append(self.dismisser)
// Return the link with whatever modification you need
return link
.isDetailLink(false)
}
}
The ViewRouter can be whatever you need. I used an ObservableObject with the intent to eventually add some Published values for more complex stack manipulation in the future:
class ViewRouter: ObservableObject {
var root: Binding<Bool>?
typealias Dismiss = () -> Void
var dismissals : [Dismiss] = []
func popToRoot() {
dismissals.forEach { dismiss in
dismiss()
}
dismissals = []
root?.wrappedValue = false
}
}
At first, I was using the solution from the Chuck H that was posted here.
But I was faced with an issue when this solution didn't work in my case. It was connected to the case when the root view is a start point for two or more flows and at some point of these flows the user has the ability to do the pop to root. And in this case this solution didn't work because it has the one common state #Environment(\.rootPresentationMode) private var rootPresentationMode
I made the RouteManager with the additional enum Route which describes some specific flow where the user has the ability to do the pop to root
RouteManager:
final class RouteManager: ObservableObject {
#Published
private var routers: [Int: Route] = [:]
subscript(for route: Route) -> Route? {
get {
routers[route.rawValue]
}
set {
routers[route.rawValue] = route
}
}
func select(_ route: Route) {
routers[route.rawValue] = route
}
func unselect(_ route: Route) {
routers[route.rawValue] = nil
}
}
Route:
enum Route: Int, Hashable {
case signUp
case restorePassword
case orderDetails
}
Usage:
struct ContentView: View {
#EnvironmentObject
var routeManager: RouteManager
var body: some View {
NavigationView {
VStack {
NavigationLink(
destination: SignUp(),
tag: .signUp,
selection: $routeManager[for: .signUp]
) { EmptyView() }.isDetailLink(false)
NavigationLink(
destination: RestorePassword(),
tag: .restorePassword,
selection: $routeManager[for: .restorePassword]
) { EmptyView() }.isDetailLink(false)
Button("Sign Up") {
routeManager.select(.signUp)
}
Button("Restore Password") {
routeManager.select(.restorePassword)
}
}
.navigationBarTitle("Navigation")
.onAppear {
routeManager.unselect(.signUp)
routeManager.unselect(.restorePassword)
}
}.navigationViewStyle(StackNavigationViewStyle())
}
}
!! IMPORTANT !!
You should use the unselect method of the RouteManager when the user goes forward to the flow and then goes back by tapping on the back button. In this case, need to reset the state of our route manager for the previously selected flows to avoid undefined (unexpected) behavior:
.onAppear {
routeManager.unselect(.signUp)
routeManager.unselect(.restorePassword)
}
You can find a full demo project here.
It's very hard to achieve with NavigationView and NavigationLink. However, if you are using the UIPilot library, which a tiny wrapper around NavigationView, popping to any destination is very straightforward.
Suppose you have routes,
enum AppRoute: Equatable {
case Home
case Detail
case NestedDetail
}
and you have setup root view like below
struct ContentView: View {
#StateObject var pilot = UIPilot(initial: AppRoute.Home)
var body: some View {
UIPilotHost(pilot) { route in
switch route {
case .Home: return AnyView(HomeView())
case .Detail: return AnyView(DetailView())
case .NestedDetail: return AnyView(NestedDetail())
}
}
}
}
And you want to pop to Home from the NestedDetail screen. Just use the popTo function.
struct NestedDetail: View {
#EnvironmentObject var pilot: UIPilot<AppRoute>
var body: some View {
VStack {
Button("Go to home", action: {
pilot.popTo(.Home) // Pop to home
})
}.navigationTitle("Nested detail")
}
}
I created a solution that "just works" and am very happy with it. To use my magic solutions, there are only a few steps you have to do.
It starts out with using rootPresentationMode that's used elsewhere in this thread. Add this code:
// Create a custom environment key
struct RootPresentationModeKey: EnvironmentKey {
static let defaultValue: Binding<RootPresentationMode> = .constant(RootPresentationMode())
}
extension EnvironmentValues {
var rootPresentationMode: Binding<RootPresentationMode> {
get { self[RootPresentationModeKey.self] }
set { self[RootPresentationModeKey.self] = newValue }
}
}
typealias RootPresentationMode = Bool
extension RootPresentationMode: Equatable {
mutating func dismiss() {
toggle()
}
}
Next comes the magic. It has two steps.
Create a view modifier that monitors changes to the rootPresentationMode variable.
struct WithRoot: ViewModifier {
#Environment(\.rootPresentationMode) private var rootPresentationMode
#Binding var rootBinding: Bool
func body(content: Content) -> some View {
content
.onChange(of: rootBinding) { newValue in
// We only care if it's set to true
if newValue {
rootPresentationMode.wrappedValue = true
}
}
.onChange(of: rootPresentationMode.wrappedValue) { newValue in
// We only care if it's set to false
if !newValue {
rootBinding = false
}
}
}
}
extension View {
func withRoot(rootBinding: Binding<Bool>) -> some View {
modifier(WithRoot(rootBinding: rootBinding))
}
}
Add an isPresented to all NavigationViews
struct ContentView: View {
// This seems.. unimportant, but it's crucial. This variable
// lets us pop back to the root view from anywhere by adding
// a withRoot() modifier
// It's only used indirectly by the withRoot() modifier.
#State private var isPresented = false
var body: some View {
NavigationView {
MyMoneyMakingApp()
}
// rootPresentationMode MUST be set on a NavigationView to be
// accessible from everywhere
.environment(\.rootPresentationMode, $isPresented)
}
To use it in (any) subviews, all you have to do is
struct MyMoneyMakingApp: View {
#State private var isActive = false
var body: some View {
VStack {
NavigationLink(destination: ADeepDeepLink(), isActive: $isActive) {
Text("go deep")
}
}
.withRoot(rootBinding: $isActive)
}
}
struct ADeepDeepLink: View {
#Environment(\.rootPresentationMode) private var rootPresentationMode
var body: some View {
VStack {
NavigationLink(destination: ADeepDeepLink()) {
Text("go deeper")
}
Button(action: {
rootPresentationMode.wrappedValue.dismiss()
}) {
Text("pop to root")
}
}
}
}
The answer from #malhal really helped out, but in my situation I needed functionality when each button was pressed before navigating. If you are in that same boat try this code out!
// ContentView.swift
// Navigation View Buttons
//
// Created by Jarren Campos on 9/10/22.
//
import SwiftUI
struct ContentView: View {
var body: some View{
VStack{
ContentView1()
}
}
}
struct ContentView1: View {
#State var isActive : Bool = false
var body: some View {
NavigationView {
VStack{
Button {
isActive = true
} label: {
Text("To 2")
}
}
.background{
NavigationLink(
destination: ContentView2(rootIsActive: self.$isActive),
isActive: self.$isActive) {}
.isDetailLink(false)
}
.navigationBarTitle("One")
}
}
}
struct ContentView2: View {
#Binding var rootIsActive : Bool
#State var toThirdView: Bool = false
var body: some View {
VStack{
Button {
toThirdView = true
} label: {
Text("to 3")
}
}
.background{
NavigationLink(isActive: $toThirdView) {
ContentView3(shouldPopToRootView: self.$rootIsActive)
} label: {}
.isDetailLink(false)
}
.navigationBarTitle("Two")
}
}
struct ContentView3: View {
#Binding var shouldPopToRootView : Bool
var body: some View {
VStack {
Text("Hello, World #3!")
Button {
self.shouldPopToRootView = false
} label: {
Text("Pop to root")
}
}
.navigationBarTitle("Three")
}
}
I don't have exactly the same issue but I do have code that changes the root view from one that doesn't support a navigation stack to one that does. The trick is that I don't do it in SwiftUI - I do it in the SceneDelegate and replace the UIHostingController with a new one.
Here's a simplified extract from my SceneDelegate:
func changeRootToOnBoarding() {
guard let window = window else {
return
}
let onBoarding = OnBoarding(coordinator: notificationCoordinator)
.environmentObject(self)
window.rootViewController = UIHostingController(rootView: onBoarding)
}
func changeRootToTimerList() {
guard let window = window else {
return
}
let listView = TimerList()
.environmentObject(self)
window.rootViewController = UIHostingController(rootView: listView)
}
Since the SceneDelegate put itself in the environment any child view can add
/// Our "parent" SceneDelegate that can change the root view.
#EnvironmentObject private var sceneDelegate: SceneDelegate
and then call public functions on the delegate. I think if you did something similar that kept the View but created a new UIHostingController for it and replaced window.rootViewController it might work for you.

How to pass one SwiftUI View as a variable to another View struct

I'm implementing a very custom NavigationLink called MenuItem and would like to reuse it across the project. It's a struct that conforms to View and implements var body : some View which contains a NavigationLink.
I need to somehow store the view that shall be presented by NavigationLink in the body of MenuItem but have yet failed to do so.
I have defined destinationView in MenuItem's body as some View and tried two initializers:
This seemed too easy:
struct MenuItem: View {
private var destinationView: some View
init(destinationView: View) {
self.destinationView = destinationView
}
var body : some View {
// Here I'm passing destinationView to NavigationLink...
}
}
--> Error: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements.
2nd try:
struct MenuItem: View {
private var destinationView: some View
init<V>(destinationView: V) where V: View {
self.destinationView = destinationView
}
var body : some View {
// Here I'm passing destinationView to NavigationLink...
}
}
--> Error: Cannot assign value of type 'V' to type 'some View'.
Final try:
struct MenuItem: View {
private var destinationView: some View
init<V>(destinationView: V) where V: View {
self.destinationView = destinationView as View
}
var body : some View {
// Here I'm passing destinationView to NavigationLink...
}
}
--> Error: Cannot assign value of type 'View' to type 'some View'.
I hope someone can help me. There must be a way if NavigationLink can accept some View as an argument.
Thanks ;D
To sum up everything I read here and the solution which worked for me:
struct ContainerView<Content: View>: View {
#ViewBuilder var content: Content
var body: some View {
content
}
}
This not only allows you to put simple Views inside, but also, thanks to #ViewBuilder, use if-else and switch-case blocks:
struct SimpleView: View {
var body: some View {
ContainerView {
Text("SimpleView Text")
}
}
}
struct IfElseView: View {
var flag = true
var body: some View {
ContainerView {
if flag {
Text("True text")
} else {
Text("False text")
}
}
}
}
struct SwitchCaseView: View {
var condition = 1
var body: some View {
ContainerView {
switch condition {
case 1:
Text("One")
case 2:
Text("Two")
default:
Text("Default")
}
}
}
}
Bonus:
If you want a greedy container, which will claim all the possible space (in contrary to the container above which claims only the space needed for its subviews) here it is:
struct GreedyContainerView<Content: View>: View {
#ViewBuilder let content: Content
var body: some View {
content
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
If you need an initializer in your view then you can use #ViewBuilder for the parameter too. Even for multiple parameters if you will:
init(#ViewBuilder content: () -> Content) {…}
The way Apple does it is using function builders. There is a predefined one called ViewBuilder. Make it the last argument, or only argument, of your init method for MenuItem, like so:
..., #ViewBuilder builder: #escaping () -> Content)
Assign it to a property defined something like this:
let viewBuilder: () -> Content
Then, where you want to diplay your passed-in views, just call the function like this:
HStack {
viewBuilder()
}
You will be able to use your new view like this:
MenuItem {
Image("myImage")
Text("My Text")
}
This will let you pass up to 10 views and use if conditions etc. though if you want it to be more restrictive you will have to define your own function builder. I haven't done that so you will have to google that.
You should make the generic parameter part of MenuItem:
struct MenuItem<Content: View>: View {
private var destinationView: Content
init(destinationView: Content) {
self.destinationView = destinationView
}
var body : some View {
// ...
}
}
You can create your custom view like this:
struct ENavigationView<Content: View>: View {
let viewBuilder: () -> Content
var body: some View {
NavigationView {
VStack {
viewBuilder()
.navigationBarTitle("My App")
}
}
}
}
struct ENavigationView_Previews: PreviewProvider {
static var previews: some View {
ENavigationView {
Text("Preview")
}
}
}
Using:
struct ContentView: View {
var body: some View {
ENavigationView {
Text("My Text")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You can pass a NavigationLink (or any other view widget) as a variable to a subview as follows:
import SwiftUI
struct ParentView: View {
var body: some View {
NavigationView{
VStack(spacing: 8){
ChildView(destinationView: Text("View1"), title: "1st")
ChildView(destinationView: Text("View2"), title: "2nd")
ChildView(destinationView: ThirdView(), title: "3rd")
Spacer()
}
.padding(.all)
.navigationBarTitle("NavigationLinks")
}
}
}
struct ChildView<Content: View>: View {
var destinationView: Content
var title: String
init(destinationView: Content, title: String) {
self.destinationView = destinationView
self.title = title
}
var body: some View {
NavigationLink(destination: destinationView){
Text("This item opens the \(title) view").foregroundColor(Color.black)
}
}
}
struct ThirdView: View {
var body: some View {
VStack(spacing: 8){
ChildView(destinationView: Text("View1"), title: "1st")
ChildView(destinationView: Text("View2"), title: "2nd")
ChildView(destinationView: ThirdView(), title: "3rd")
Spacer()
}
.padding(.all)
.navigationBarTitle("NavigationLinks")
}
}
The accepted answer is nice and simple. The syntax got even cleaner with iOS 14 + macOS 11:
struct ContainerView<Content: View>: View {
#ViewBuilder var content: Content
var body: some View {
content
}
}
Then continue to use it like this:
ContainerView{
...
}
I really struggled to make mine work for an extension of View. Full details about how to call it are seen here.
The extension for View (using generics) - remember to import SwiftUI:
extension View {
/// Navigate to a new view.
/// - Parameters:
/// - view: View to navigate to.
/// - binding: Only navigates when this condition is `true`.
func navigate<SomeView: View>(to view: SomeView, when binding: Binding<Bool>) -> some View {
modifier(NavigateModifier(destination: view, binding: binding))
}
}
// MARK: - NavigateModifier
fileprivate struct NavigateModifier<SomeView: View>: ViewModifier {
// MARK: Private properties
fileprivate let destination: SomeView
#Binding fileprivate var binding: Bool
// MARK: - View body
fileprivate func body(content: Content) -> some View {
NavigationView {
ZStack {
content
.navigationBarTitle("")
.navigationBarHidden(true)
NavigationLink(destination: destination
.navigationBarTitle("")
.navigationBarHidden(true),
isActive: $binding) {
EmptyView()
}
}
}
}
}
Alternatively you can use a static function extension. For example, I make a titleBar extension to Text. This makes it very easy to reuse code.
In this case you can pass a #Viewbuilder wrapper with the view closure returning a custom type that conforms to view. For example:
import SwiftUI
extension Text{
static func titleBar<Content:View>(
titleString:String,
#ViewBuilder customIcon: ()-> Content
)->some View {
HStack{
customIcon()
Spacer()
Text(titleString)
.font(.title)
Spacer()
}
}
}
struct Text_Title_swift_Previews: PreviewProvider {
static var previews: some View {
Text.titleBar(titleString: "title",customIcon: {
Image(systemName: "arrowshape.turn.up.backward")
})
.previewLayout(.sizeThatFits)
}
}
If anyone is trying to pass two different views to other view, and can't do it because of this error:
Failed to produce diagnostic for expression; please submit a bug report...
Because we are using <Content: View>, the first view you passed, the view is going to store its type, and expect the second view you are passing be the same type, this way, if you want to pass a Text and an Image, you will not be able to.
The solution is simple, add another content view, and name it differently.
Example:
struct Collapsible<Title: View, Content: View>: View {
#State var title: () -> Title
#State var content: () -> Content
#State private var collapsed: Bool = true
var body: some View {
VStack {
Button(
action: { self.collapsed.toggle() },
label: {
HStack {
self.title()
Spacer()
Image(systemName: self.collapsed ? "chevron.down" : "chevron.up")
}
.padding(.bottom, 1)
.background(Color.white.opacity(0.01))
}
)
.buttonStyle(PlainButtonStyle())
VStack {
self.content()
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: collapsed ? 0 : .none)
.clipped()
.animation(.easeOut)
.transition(.slide)
}
}
}
Calling this View:
Collapsible {
Text("Collapsible")
} content: {
ForEach(1..<5) { index in
Text("\(index) test")
}
}
Syntax for 2 Views
struct PopOver<Content, PopView> : View where Content: View, PopView: View {
var isShowing: Bool
#ViewBuilder var content: () -> Content
#ViewBuilder var popover: () -> PopView
var body: some View {
ZStack(alignment: .center) {
self
.content()
.disabled(isShowing)
.blur(radius: isShowing ? 3 : 0)
ZStack {
self.popover()
}
.frame(width: 112, height: 112)
.opacity(isShowing ? 1 : 0)
.disabled(!isShowing)
}
}
}

SwiftUI - Is there a popViewController equivalent in SwiftUI?

I was playing around with SwiftUI and want to be able to come back to the previous view when tapping a button, the same we use popViewController inside a UINavigationController.
Is there a provided way to do it so far ?
I've also tried to use NavigationDestinationLink to do so without success.
struct AView: View {
var body: some View {
NavigationView {
NavigationButton(destination: BView()) {
Text("Go to B")
}
}
}
}
struct BView: View {
var body: some View {
Button(action: {
// Trying to go back to the previous view
// previously: navigationController.popViewController(animated: true)
}) {
Text("Come back to A")
}
}
}
Modify your BView struct as follows. The button will perform just as popViewController did in UIKit.
struct BView: View {
#Environment(\.presentationMode) var mode: Binding<PresentationMode>
var body: some View {
Button(action: { self.mode.wrappedValue.dismiss() })
{ Text("Come back to A") }
}
}
Use #Environment(\.presentationMode) var presentationMode to go back previous view. Check below code for more understanding.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
ZStack {
Color.gray.opacity(0.2)
NavigationLink(destination: NextView(), label: {Text("Go to Next View").font(.largeTitle)})
}.navigationBarTitle(Text("This is Navigation"), displayMode: .large)
.edgesIgnoringSafeArea(.bottom)
}
}
}
struct NextView: View {
#Environment(\.presentationMode) var presentationMode
var body: some View {
ZStack {
Color.gray.opacity(0.2)
}.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}, label: { Image(systemName: "arrow.left") }))
.navigationBarTitle("", displayMode: .inline)
}
}
struct NameRow: View {
var name: String
var body: some View {
HStack {
Image(systemName: "circle.fill").foregroundColor(Color.green)
Text(name)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
With State Variables. Try that.
struct ContentViewRoot: View {
#State var pushed: Bool = false
var body: some View {
NavigationView{
VStack{
NavigationLink(destination:ContentViewFirst(pushed: self.$pushed), isActive: self.$pushed) { EmptyView() }
.navigationBarTitle("Root")
Button("push"){
self.pushed = true
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentViewFirst: View {
#Binding var pushed: Bool
#State var secondPushed: Bool = false
var body: some View {
VStack{
NavigationLink(destination: ContentViewSecond(pushed: self.$pushed, secondPushed: self.$secondPushed), isActive: self.$secondPushed) { EmptyView() }
.navigationBarTitle("1st")
Button("push"){
self.secondPushed = true;
}
}
}
}
struct ContentViewSecond: View {
#Binding var pushed: Bool
#Binding var secondPushed: Bool
var body: some View {
VStack{
Spacer()
Button("PopToRoot"){
self.pushed = false
} .navigationBarTitle("2st")
Spacer()
Button("Pop"){
self.secondPushed = false
} .navigationBarTitle("1st")
Spacer()
}
}
}
This seems to work for me on watchOS (haven't tried on iOS):
#Environment(\.presentationMode) var presentationMode
And then when you need to pop
self.presentationMode.wrappedValue.dismiss()
There is now a way to programmatically pop in a NavigationView, if you would like. This is in beta 5.
Notice that you don't need the back button. You could programmatically trigger the showSelf property in the DetailView any way you like. And you don't have to display the "Push" text in the master. That could be an EmptyView(), thereby creating an invisible segue.
(The new NavigationLink functionality takes over the deprecated NavigationDestinationLink)
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
MasterView()
}
}
}
struct MasterView: View {
#State var showDetail = false
var body: some View {
VStack {
NavigationLink(destination: DetailView(showSelf: $showDetail), isActive: $showDetail) {
Text("Push")
}
}
}
}
struct DetailView: View {
#Binding var showSelf: Bool
var body: some View {
Button(action: {
self.showSelf = false
}) {
Text("Pop")
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
It seems that a ton of basic navigation functionality is super buggy, which is disappointing and may be worth walking away from for now to save hours of frustration. For me, PresentationButton is the only one that works. TabbedView tabs don't work properly, and NavigationButton doesn't work for me at all. Sounds like YMMV if NavigationButton works for you.
I'm hoping that they fix it at the same time they fix autocomplete, which would give us much better insight as to what is available to us. In the meantime, I'm reluctantly coding around it and keeping notes for when fixes come out. It sucks to have to figure out if we're doing something wrong or if it just doesn't work, but that's beta for you!
Update: the NavigationDestinationLink API in this solution has been deprecated as of iOS 13 Beta 5. It is now recommended to use NavigationLink with an isActive binding.
I figured out a solution for programmatic pushing/popping of views in a NavigationView using NavigationDestinationLink.
Here's a simple example:
import Combine
import SwiftUI
struct DetailView: View {
var onDismiss: () -> Void
var body: some View {
Button(
"Here are details. Tap to go back.",
action: self.onDismiss
)
}
}
struct MainView: View {
var link: NavigationDestinationLink<DetailView>
var publisher: AnyPublisher<Void, Never>
init() {
let publisher = PassthroughSubject<Void, Never>()
self.link = NavigationDestinationLink(
DetailView(onDismiss: { publisher.send() }),
isDetail: false
)
self.publisher = publisher.eraseToAnyPublisher()
}
var body: some View {
VStack {
Button("I am root. Tap for more details.", action: {
self.link.presented?.value = true
})
}
.onReceive(publisher, perform: { _ in
self.link.presented?.value = false
})
}
}
struct RootView: View {
var body: some View {
NavigationView {
MainView()
}
}
}
I wrote about this in a blog post here.
You can also do it with .sheet
.navigationBarItems(trailing: Button(action: {
self.presentingEditView.toggle()
}) {
Image(systemName: "square.and.pencil")
}.sheet(isPresented: $presentingEditView) {
EditItemView()
})
In my case I use it from a right navigation bar item, then you have to create the view (EditItemView() in my case) that you are going to display in that modal view.
https://developer.apple.com/documentation/swiftui/view/sheet(ispresented:ondismiss:content:)
EDIT: This answer over here is better than mine, but both work: SwiftUI dismiss modal
What you really want (or should want) is a modal presentation, which several people have mentioned here. If you go that path, you definitely will need to be able to programmatically dismiss the modal, and Erica Sadun has a great example of how to do that here: https://ericasadun.com/2019/06/16/swiftui-modal-presentation/
Given the difference between declarative coding and imperative coding, the solution there may be non-obvious (toggling a bool to false to dismiss the modal, for example), but it makes sense if your model state is the source of truth, rather than the state of the UI itself.
Here's my quick take on Erica's example, using a binding passed into the TestModal so that it can dismiss itself without having to be a member of the ContentView itself (as Erica's is, for simplicity).
struct TestModal: View {
#State var isPresented: Binding<Bool>
var body: some View {
Button(action: { self.isPresented.value = false }, label: { Text("Done") })
}
}
struct ContentView : View {
#State var modalPresented = false
var body: some View {
NavigationView {
Text("Hello World")
.navigationBarTitle(Text("View"))
.navigationBarItems(trailing:
Button(action: { self.modalPresented = true }) { Text("Show Modal") })
}
.presentation(self.modalPresented ? Modal(TestModal(isPresented: $modalPresented)) {
self.modalPresented.toggle()
} : nil)
}
}
Below works for me in XCode11 GM
self.myPresentationMode.wrappedValue.dismiss()
instead of NavigationButton use Navigation DestinationLink
but You should import Combine
struct AView: View {
var link: NavigationDestinationLink<BView>
var publisher: AnyPublisher<Void, Never>
init() {
let publisher = PassthroughSubject<Void, Never>()
self.link = NavigationDestinationLink(
BView(onDismiss: { publisher.send() }),
isDetail: false
)
self.publisher = publisher.eraseToAnyPublisher()
}
var body: some View {
NavigationView {
Button(action:{
self.link.presented?.value = true
}) {
Text("Go to B")
}.onReceive(publisher, perform: { _ in
self.link.presented?.value = false
})
}
}
}
struct BView: View {
var onDismiss: () -> Void
var body: some View {
Button(action: self.onDismiss) {
Text("Come back to A")
}
}
}
In the destination pass the view you want to redirect, and inside block pass data you to pass in another view.
NavigationLink(destination: "Pass the particuter View") {
Text("Push")
}

Custom back button for NavigationView's navigation bar in SwiftUI

I want to add a custom navigation button that will look somewhat like this:
Now, I've written a custom BackButton view for this. When applying that view as leading navigation bar item, by doing:
.navigationBarItems(leading: BackButton())
...the navigation view looks like this:
I've played around with modifiers like:
.navigationBarItem(title: Text(""), titleDisplayMode: .automatic, hidesBackButton: true)
without any luck.
Question
How can I...
set a view used as custom back button in the navigation bar? OR:
programmatically pop the view back to its parent?
When going for this approach, I could hide the navigation bar altogether using .navigationBarHidden(true)
TL;DR
Use this to transition to your view:
NavigationLink(destination: SampleDetails()) {}
Add this to the view itself:
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
Then, in a button action or something, dismiss the view:
presentationMode.wrappedValue.dismiss()
Full code
From a parent, navigate using NavigationLink
NavigationLink(destination: SampleDetails()) {}
In DetailsView hide navigationBarBackButton and set custom back button to leading navigationBarItem,
struct SampleDetails: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var btnBack : some View { Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image("ic_back") // set image here
.aspectRatio(contentMode: .fit)
.foregroundColor(.white)
Text("Go back")
}
}
}
var body: some View {
List {
Text("sample code")
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: btnBack)
}
}
SwiftUI 1.0
It looks like you can now combine the navigationBarBackButtonHidden and .navigationBarItems to get the effect you're trying to achieve.
Code
struct Navigation_CustomBackButton_Detail: View {
#Environment(\.presentationMode) var presentationMode
var body: some View {
ZStack {
Color("Theme3BackgroundColor")
VStack(spacing: 25) {
Image(systemName: "globe").font(.largeTitle)
Text("NavigationView").font(.largeTitle)
Text("Custom Back Button").foregroundColor(.gray)
HStack {
Image("NavBarBackButtonHidden")
Image(systemName: "plus")
Image("NavBarItems")
}
Text("Hide the system back button and then use the navigation bar items modifier to add your own.")
.frame(maxWidth: .infinity)
.padding()
.background(Color("Theme3ForegroundColor"))
.foregroundColor(Color("Theme3BackgroundColor"))
Spacer()
}
.font(.title)
.padding(.top, 50)
}
.navigationBarTitle(Text("Detail View"), displayMode: .inline)
.edgesIgnoringSafeArea(.bottom)
// Hide the system back button
.navigationBarBackButtonHidden(true)
// Add your custom back button here
.navigationBarItems(leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}
Example
Here is what it looks like (excerpt from the "SwiftUI Views" book):
Based on other answers here, this is a simplified answer for Option 2 working for me in XCode 11.0:
struct DetailView: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Image(systemName: "gobackward").padding()
}
.navigationBarHidden(true)
}
}
Note: To get the NavigationBar to be hidden, I also needed to set and then hide the NavigationBar in ContentView.
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailView()) {
Text("Link").padding()
}
} // Main VStack
.navigationBarTitle("Home")
.navigationBarHidden(true)
} //NavigationView
}
}
Here's a more condensed version using principles shown in the other comments to change only the text of the button. The chevron.left icon can also be easily replaced with another icon.
Create your own button, then assign it using .navigationBarItems(). I found the following format most nearly approximated the default back button.
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var backButton : some View {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack(spacing: 0) {
Image(systemName: "chevron.left")
.font(.title2)
Text("Cancel")
}
}
}
Make sure you use .navigationBarBackButtonHidden(true) to hide the default button and replace it with your own!
List(series, id:\.self, selection: $selection) { series in
Text(series.SeriesLabel)
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: backButton)
iOS 15+
presentationMode.wrappedValue.dismiss() is now deprecated.
It's replaced by DismissAction
private struct SheetContents: View {
#Environment(\.dismiss) private var dismiss
var body: some View {
Button("Done") {
dismiss()
}
}
}
You can create a custom back button that will use this dismiss action
struct NavBackButton: View {
let dismiss: DismissAction
var body: some View {
Button {
dismiss()
} label: {
Image("...custom back button here")
}
}
}
then attach it to your view.
.navigationBarBackButtonHidden(true) // Hide default button
.navigationBarItems(leading: NavBackButton(dismiss: self.dismiss)) // Attach custom button
I expect you want to use custom back button in all navigable screens,
so I wrote custom wrapper based on #Ashish answer.
struct NavigationItemContainer<Content>: View where Content: View {
private let content: () -> Content
#Environment(\.presentationMode) var presentationMode
private var btnBack : some View { Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image("back_icon") // set image here
.aspectRatio(contentMode: .fit)
.foregroundColor(.black)
Text("Go back")
}
}
}
var body: some View {
content()
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: btnBack)
}
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
}
Wrap screen content in NavigationItemContainer:
Usage:
struct CreateAccountScreenView: View {
var body: some View {
NavigationItemContainer {
VStack(spacing: 21) {
AppLogoView()
//...
}
}
}
}
Swiping is not disabled this way.
Works for me. XCode 11.3.1
Put this in your root View
init() {
UINavigationBar.appearance().isUserInteractionEnabled = false
UINavigationBar.appearance().backgroundColor = .clear
UINavigationBar.appearance().barTintColor = .clear
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().tintColor = .clear
}
And this in your child View
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
Button(action: {self.presentationMode.wrappedValue.dismiss()}) {
Image(systemName: "gobackward")
}
You can use UIAppearance for this:
if let image = UIImage(named: "back-button") {
UINavigationBar.appearance().backIndicatorImage = image
UINavigationBar.appearance().backIndicatorTransitionMaskImage = image
}
This should be added early on in your app like App.init. This also preserves the native swipe back functionality.
All of the solutions I see here seem to disable swipe to go back functionality to navigate to the previous page, so sharing a solution I found that maintains that functionality. You can make an extension of your root view and override your navigation style and call the function in the view initializer.
Sample View
struct SampleRootView: View {
init() {
overrideNavigationAppearance()
}
var body: some View {
Text("Hello, World!")
}
}
Extension
extension SampleRootView {
func overrideNavigationAppearance() {
let navigationBarAppearance = UINavigationBarAppearance()
let barAppearace = UINavigationBar.appearance()
barAppearace.tintColor = *desired UIColor for icon*
barAppearace.barTintColor = *desired UIColor for icon*
navigationBarAppearance.setBackIndicatorImage(*desired UIImage for custom icon*, transitionMaskImage: *desired UIImage for custom icon*)
UINavigationBar.appearance().standardAppearance = navigationBarAppearance
UINavigationBar.appearance().compactAppearance = navigationBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance
}
}
The only downfall to this approach is I haven't found a way to remove/change the text associated with the custom back button.
Really simple method. Only two lines code 🔥
#Environment(\.presentationMode) var presentationMode
self.presentationMode.wrappedValue.dismiss()
Example:
import SwiftUI
struct FirstView: View {
#State var showSecondView = false
var body: some View {
NavigationLink(destination: SecondView(),isActive : self.$showSecondView){
Text("Push to Second View")
}
}
}
struct SecondView : View{
#Environment(\.presentationMode) var presentationMode
var body : some View {
Button(action:{ self.presentationMode.wrappedValue.dismiss() }){
Text("Go Back")
}
}
}
This solution works for iPhone. However, for iPad it won't work because of the splitView.
import SwiftUI
struct NavigationBackButton: View {
var title: Text?
#Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
var body: some View {
ZStack {
VStack {
ZStack {
HStack {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Image(systemName: "chevron.left")
.font(.title)
.frame(width: 44, height: 44)
title
}
Spacer()
}
}
Spacer()
}
}
.zIndex(1)
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
struct NavigationBackButton_Previews: PreviewProvider {
static var previews: some View {
NavigationBackButton()
}
}
I found this: https://ryanashcraft.me/swiftui-programmatic-navigation/
It does work, and it may lay the foundation for a state machine to control what is showing, but it is not a simple as it was before.
import Combine
import SwiftUI
struct DetailView: View {
var onDismiss: () -> Void
var body: some View {
Button(
"Here are details. Tap to go back.",
action: self.onDismiss
)
}
}
struct RootView: View {
var link: NavigationDestinationLink<DetailView>
var publisher: AnyPublisher<Void, Never>
init() {
let publisher = PassthroughSubject<Void, Never>()
self.link = NavigationDestinationLink(
DetailView(onDismiss: { publisher.send() }),
isDetail: false
)
self.publisher = publisher.eraseToAnyPublisher()
}
var body: some View {
VStack {
Button("I am root. Tap for more details.", action: {
self.link.presented?.value = true
})
}
.onReceive(publisher, perform: { _ in
self.link.presented?.value = false
})
}
}
struct ContentView: View {
var body: some View {
NavigationView {
RootView()
}
}
}
If you want to hide the button then you can replace the DetailView with this:
struct LocalDetailView: View {
var onDismiss: () -> Void
var body: some View {
Button(
"Here are details. Tap to go back.",
action: self.onDismiss
)
.navigationBarItems(leading: Text(""))
}
}
Just write this:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
}.onAppear() {
UINavigationBar.appearance().tintColor = .clear
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "back")?.withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "back")?.withRenderingMode(.alwaysOriginal)
}
}
}
On iOS 14+ it's actually very easy using presentationMode variable
In this example NewItemView will get dismissed on addItem completion:
struct NewItemView: View {
#State private var itemDescription:String = ""
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
TextEditor(text: $itemDescription)
}.onTapGesture {
hideKeyboard()
}.toolbar {
ToolbarItem {
Button(action: addItem){
Text("Save")
}
}
}.navigationTitle("Add Question")
}
private func addItem() {
// Add save logic
// ...
// Dismiss on complete
presentationMode.wrappedValue.dismiss()
}
private func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
struct NewItemView_Previews: PreviewProvider {
static var previews: some View {
NewItemView()
}
}
In case you need the parent (Main) view:
struct SampleMainView: View {
#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \DbQuestion.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink {
Text("This is item detail page")
} label: {
Text("Item at \(item.id)")
}
}
}
.toolbar {
ToolbarItem {
// Creates a button on toolbar
NavigationLink {
// New Item Page
NewItemView()
} label: {
Text("Add item")
}
}
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
}.navigationTitle("Main Screen")
}
}
}