0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NavigationView を NavigationStack に置き換える

Posted at

NavigationView を NavigationStack に置き換えると、次のような変化と利点があります。

✅ NavigationStack に置き換えた場合の挙動
iPhone / iPad 両方とも:
常にスタック型UI(=iPhoneと同じ見た目)になります。

NavigationView NavigationStack
Simulator Screenshot - iPad Air 13-inch (M3) - 2025-08-14 at 10.31.40.png Simulator Screenshot - iPad Air 13-inch (M3) - 2025-08-14 at 10.38.29.png

iPadでも勝手にサイドバー(Split View)にならない。

よって、今回の「iPadでもiPhoneと同じ表示にしたい」目的に最適です。

✅ コードの変更点(簡単)
NavigationView を 以下のように変更するだけです:

Before

NavigationView {
  VStack {
    // ...
  }
}
import SwiftUI

struct BasicNavigationView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink("次の画面へ", destination: Text("詳細画面"))
            }
            .navigationTitle("ホーム")
        }
    }
}

After

NavigationStack {
  VStack {
    // ...
  }
}
import SwiftUI

// 遷移先を管理する enum(Hashable 必須)
enum Screen: Hashable {
    case detail(String)
    case settings
}

struct AdvancedNavigationView: View {
    @State private var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            VStack(spacing: 16) {
                Button("詳細画面へ") {
                    path.append(Screen.detail("データ付き画面"))
                }
                Button("設定画面へ") {
                    path.append(Screen.settings)
                }
            }
            .navigationTitle("ホーム")
            .navigationDestination(for: Screen.self) { screen in
                switch screen {
                case .detail(let message):
                    Text("詳細: \(message)")
                case .settings:
                    SettingsView()
                }
            }
        }
    }
}

struct SettingsView: View {
    var body: some View {
        Text("設定画面")
    }
}

navigationBarItems, navigationBarTitleDisplayMode などはそのまま使えます。
ただし NavigationStack は iOS 16 以降が必要です。

✅ NavigationStack にするメリット

項目 NavigationView NavigationStack
iPadでの表示 自動でSidebarになる iPhoneと同じスタック表示
型安全なナビゲーション 弱い 強い(パス管理可能)
新しいAPI対応 非推奨(iOS 16以降) 推奨
複雑なナビゲーション制御 難しい 可能(NavigationPath

✅ 注意点
NavigationStack は iOS 16以降が必要。

iOS 15以前をサポートしている場合は NavigationView を維持 or 条件分岐が必要。

NavigationLink の使い方が少し違う(value: を使ってパス指定できる)。

✅ 結論
iPadでもiPhoneと同じ見た目にしたくて、iOS 16以上をサポートしているなら:

NavigationView → NavigationStack に置き換えるのがベストです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?