1
1

More than 3 years have passed since last update.

[SwiftUI] 画面遷移に関して

Posted at

今回はSwiftUIの画面遷移に関して解説していきます。

遷移後画面の作成

command + Nで新たなファイルを作成します。
SwiftUI Viewを選択してください。
その後createで作成します。


import SwiftUI

struct SecondView: View {
    var body: some View {
        Text("画面遷移出来たよ!")
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SecondView()
    }
}

上のコードはSecondViewとし、Textも"画面遷移出来たよ!"と変更しましたが変えても変えなくてもどちらでも良いです。

遷移前画面の作成


import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: SecondView()) {
                Text("押したら画面が変わるよ")
                    .padding()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

NavigationLinkでTextをタップしたときに画面遷移が行えるようにしています。
またNavigationViewNavigationLinkを使用する場合に必要となります。

destination:の部分には遷移先の画面を指定します。
今回は先程作成したSecondViewをしていますね。

完成

これが遷移前の画面で、ボタンを押すと…
スクショ1





うまく画面が切り替わりましたね。
スクショ1
お疲れ様でした。
ここまでご覧いただきありがとうございます。






余談ですがNavigationLinkに含まれるTextを下のように変えることで


                Text("押したら画面が変わるよ")
                    .font(.title)
                    .frame(width: 400, height: 48)
                    .foregroundColor(Color(.blue))
                    .background(Color(.green))
                    .overlay(
                        RoundedRectangle(cornerRadius: 0)
                            .stroke(Color(.red), lineWidth: 1.0)
                    )

このようなボタンのようなTextが作成できます。

スクショ1

1
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
1
1