LoginSignup
8
6

More than 1 year has passed since last update.

[SwiftUI] 変数の値をNavigationLinkのdestinationに指定して画面遷移できるようにしたい。

Last updated at Posted at 2021-10-08

概要

使いまわせるviewは、できるだけ細かく作って、車輪の再開発だけは避けたい!!!
と思い、List用のcellのviewを作成。
しかし、cellにあるNavigationLinkのdestinationプロパティの値で怒られ、ハマる。。。

Cannot find type 'Destination' in scopeで怒られ、引数に遷移したいviewを渡せない。。。

スクリーンショット 2021-10-08 21.55.36.png

struct NavigationLinkView: View {

    var body: some View {
        VStack(spacing: 30) {
            NavigationLinkCell(title: "home", destination: HomeView())
            NavigationLinkCell(title: "favorite", destination: FavoriteView())
            NavigationLinkCell(title: "test", destination: TestView())
        }
    }
}

struct NavigationLinkCell: View{

    let title: String
    let destination: Destination

    var body: some View {
        NavigationLink(destination: destination) {
            Text(title)
        }
    }
}

struct HomeView: View {
    var body: some View {
        Text("HomeView")
    }
}

struct FavoriteView: View {
    var body: some View {
        Text("FavoriteView")
    }
}

struct TestView: View {
    var body: some View {
        Text("TestView")
    }
}

解決策

"Destination : View"  型をつけてやります。

struct NavigationLinkCell<Destination : View>: View{

    let title: String
    let destination: Destination

    var body: some View {
        NavigationLink(destination: destination) {
            Text(title)
        }
    }
}

スクリーンショット 2021-10-08 22.01.49.png

8
6
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
8
6