Created
July 2, 2025 10:23
-
-
Save CH3COOH/d7cff0c552200c1429dc4e53e8136165 to your computer and use it in GitHub Desktop.
Xcode 16.4以降、NavigationStack の挙動がおかしい
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// SampleNavigationStackOnAppear | |
// | |
// Created by wada.kenji on 2025/07/02. | |
// | |
import os | |
import SwiftUI | |
public enum Logger { | |
public static let standard: os.Logger = .init( | |
subsystem: Bundle.main.bundleIdentifier!, | |
category: "Standard" | |
) | |
} | |
enum Route: Hashable { | |
case screenA | |
case screenB | |
case screenC | |
case screenD | |
} | |
class Router: ObservableObject { | |
@Published | |
private(set) var path = NavigationPath() | |
func setPath(path: NavigationPath) { | |
self.path = path | |
} | |
func present(route: Route) { | |
path.append(route) | |
} | |
func pop() { | |
path.removeLast() | |
} | |
func popToRoot() { | |
path.removeLast(path.count) | |
} | |
} | |
struct ContentView: View { | |
@StateObject | |
private var router = Router() | |
var body: some View { | |
NavigationStack(path: .init( | |
get: { router.path }, | |
set: { router.setPath(path: $0) } | |
)) { | |
DummyScreen(screenName: "ScreenA") { | |
router.present(route: .screenB) | |
} | |
.navigationDestination(for: Route.self) { route in | |
switch route { | |
case .screenA: | |
DummyScreen(screenName: "ScreenA") { | |
router.present(route: .screenB) | |
} | |
case .screenB: | |
DummyScreen(screenName: "ScreenB") { | |
router.present(route: .screenC) | |
} | |
case .screenC: | |
DummyScreen(screenName: "ScreenC") { | |
router.present(route: .screenD) | |
} | |
case .screenD: | |
DummyScreen(screenName: "ScreenD", action: nil) | |
} | |
} | |
} | |
.environmentObject(router) | |
} | |
} | |
struct DummyScreen: View { | |
@EnvironmentObject var router: Router | |
let screenName: String | |
let action: (() -> Void)? | |
var body: some View { | |
VStack { | |
Text(screenName) | |
.font(.title) | |
if let action { | |
Button("Go to next screen", action: action) | |
} | |
} | |
.navigationTitle(Text(screenName)) | |
.onAppear { | |
Logger.standard.debug("\(screenName) の onAppear") | |
} | |
} | |
} | |
@main | |
struct SampleNavigationStackOnAppearApp: App { | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment