Skip to content

Instantly share code, notes, and snippets.

@danhalliday
Created February 29, 2024 09:27
Show Gist options
  • Save danhalliday/9220973261e19726ef939f06cc99d0de to your computer and use it in GitHub Desktop.
Save danhalliday/9220973261e19726ef939f06cc99d0de to your computer and use it in GitHub Desktop.
SwiftUINavigation Test Case
import SwiftUI
import SwiftUINavigation
import XCTestDynamicOverlay
// MARK: - Screen One
@MainActor class ScreenOne: ObservableObject {
@CasePathable
@dynamicMemberLookup
enum Destination {
case two(ScreenTwo)
}
@Published var destination: Destination? {
didSet {
destination?.two?.onBack = {
[weak self] in self?.destination = nil
}
}
}
}
struct ScreenOneView: View {
@ObservedObject var model: ScreenOne
var body: some View {
List {
Button("Show Screen Two") {
model.destination = .two(ScreenTwo())
}
}
.navigationTitle("Screen One")
.navigationDestination(
unwrapping: $model.destination.two,
destination: { $model in ScreenTwoView(model: model) }
)
}
}
// MARK: - Screen Two
@MainActor class ScreenTwo: ObservableObject {
@CasePathable
@dynamicMemberLookup
enum Destination {
case three(ScreenThree)
}
@Published var destination: Destination? {
didSet {
destination?.three?.onBack = {
[weak self] in self?.destination = nil
}
}
}
var onBack: () -> Void = unimplemented()
}
struct ScreenTwoView: View {
@ObservedObject var model: ScreenTwo
var body: some View {
List {
Button("Show Screen Three") {
model.destination = .three(ScreenThree())
}
Button("Go Back") {
model.onBack()
}
}
.navigationTitle("Screen Two")
.navigationDestination(
unwrapping: $model.destination.three,
destination: { $model in ScreenThreeView(model: model) }
)
}
}
// MARK: - Screen Three
@MainActor class ScreenThree: ObservableObject {
var onBack: () -> Void = unimplemented()
}
struct ScreenThreeView: View {
@ObservedObject var model: ScreenThree
var body: some View {
List {
Button("Go Back") {
model.onBack()
}
}
.navigationTitle("Screen Three")
}
}
// MARK: - Previews
#Preview {
ScreenOneView(model: ScreenOne())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment