
今回はSwiftUI内で画面遷移をする実装を解説します。
簡単なのでサクッと覚えてしまいましょう!
◉今回の完成図

Contents 非表示
開発環境
今回は以下の環境で実装しています
Mac OS | 12.4 |
Swift | 5.6 |
Xcode | 13.3 |
プロジェクトの作成、ファイル追加 & 装飾
プロジェクト作成
テキトーにプロジェクトを作成しましょう

遷移先のファイルを準備
今回はナビゲーション遷移 & モーダル遷移の実装を行うので新たに2つファイルを追加します。
◉まずはナビゲーション遷移用
Command + Nで新規ファイル作成画面を開く & SwiftUI Viewを選択

◉モーダル用も同様に

両方ファイルが作成出来たことが確認出来たら次のセクションに移りましょう

ナビゲーション遷移
ナビゲーション遷移とは、左から右に流れるアニメーションの遷移です
戻るボタンは勝手に作成されるので気にしなくてOKです。
コード記述
それではコードを書いていきましょう、まずはコピペしてください(解説は後述します)
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: SecondView().navigationTitle("遷移先だよ")) {
Text("ナビゲーション遷移だよ")
.font(.system(size: 30))
.foregroundColor(.white)
.padding()
.background(.orange)
.cornerRadius(10)
}
}
.navigationTitle("画面1")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

import SwiftUI
struct SecondView: View {
var body: some View {
ZStack {
Color(.yellow)
Text("This is ナビゲーション遷移")
.font(.system(size: 30))
}
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}

ビルド
一旦ビルドをして、ナビゲーション遷移がどのような動きをするのか見てみましょう。

解説した通り、横に流れる遷移ですね。
iPhoneの設定アプリがいい例だと思います、時間がある時に確認してみてください。

モーダル遷移
モーダル遷移とは、画面下からピョコッと出てくるアニメーションの遷移です
コード記述
import SwiftUI
struct ContentView: View {
@State var isShowThirdView = false
var body: some View {
VStack{
NavigationView {
VStack {
NavigationLink(destination: SecondView().navigationTitle("遷移先だよ")) {
Text("ナビゲーション遷移だよ")
.font(.system(size: 30))
.foregroundColor(.white)
.padding()
.background(.orange)
.cornerRadius(10)
}
Button(action: {
isShowThirdView = true
}) {
Text("モーダル遷移するよ")
.font(.system(size: 30))
.foregroundColor(.white)
.padding()
.background(.green)
.cornerRadius(10)
.padding(40)
}
.sheet(isPresented: $isShowThirdView) {
ThirdView()
}
}
.navigationTitle("最初の画面だよ")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

import SwiftUI
struct ThirdView: View {
var body: some View {
ZStack {
Color(.orange)
Text("This is モーダル遷移")
.font(.system(size: 30))
}
}
}
struct ThirdView_Previews: PreviewProvider {
static var previews: some View {
ThirdView()
}
}

ビルド
それではビルドをしてどのように遷移の動きを確認しましょう。

これに関してはパッといい例が思いつきませんでしたが、、、
例えばApple純正のカレンダーアプリとかですかね、新規作成ボタンを押すとモーダル遷移がされるので時間が有れば確認してみてください。

☆今回参考にさせて頂いたサイト
まとめ

今回は以上です、画面遷移はアプリを作る上でほぼ必須の実装だと思うのでしっかりと覚えておきましょう。