SwiftUI is continuously improving, and with SwiftUI supporting iOS 16.0 and later, it offers NavigationPath
which makes it easier for us to manage navigation and pop
or push
views. Although it has addressed some limitations of older versions, there are still some issues with popping back to a specific view and identifying the items currently inside the NavigationStack.
I have extended it in a way that is purely SwiftUI, using only what is available and writing it in the most basic way possible.
Now we can pop to any View
in the NavigationStack
based on the Codable
objects we have appended
to the NavigationPath
.
Check out the demo video below and use it if it can help you in your project.
To run the example project, clone the repo, and run pod install
from the Example directory first.
- iOS 16.0 or later
- Swift 5+
PureNavigationPath is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'PureNavigationPath'
Create NavigationStack
with NavigationPath
Declare the Destinations
NavigationStack(path: $path) {
// ***
}
.navigationDestination(type: BookCategory.self, destination: { category in
ViewB(category: category)
})
.navigationDestination(type: Book.self, destination: { book in
ViewC(book: book)
})
.navigationDestination(type: String.self, destination: { path in
ViewD(path: path)
})
.navigationDestination(type: Int.self, destination: { intPath in
ViewE(intPath: intPath)
})
Push to destinations according to the type defined above by appending Codable to the path.
struct Book: Identifiable, Hashable, Codable {}
let book = Book() // Codable struct
path.append(book)
enum BookCategory: Identifiable, Hashable, Codable {}
let category = BookCategory()
path.append(category)
let pathString = "examplePath"
path.append(pathString)
let pathInteger = 100
path.append(pathInteger)
Dismiss top view of navigation.
path.pop()
Pop to any View based on the original codable appended.
path.pop(to: book)
path.pop(to: category)
path.pop(to: "examplePath")
path.pop(to: 100)
path.popToRoot()
print(path.resolvedItems())
/*
[
1,
"ViewD",
Example.Book(id: "253D9737-51B7-44FF-A3F2-55C0ADF0AF35", name: "To Kill a Mockingbird", author: "Harper Lee", page: 281),
Example.BookCategory.new
]
*/
Contact for work.
PureNavigationPath is available under the MIT license. See the LICENSE file for more info.