SwiftUIで画面遷移時に値を渡す
SwiftUIで画面遷移時に値を渡す方法です。
ContentView
ではフルーツの一覧を表示しています。
フルーツが表示されたセルを押すと SecondView
に遷移し、選択されたセルのフルーツ名が表示されます。
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
import SwiftUI | |
struct ContentView: View { | |
let fruits = ["Apple", "Banana", "Orange", "Grape", "Cherry", "Peach"] | |
var body: some View { | |
NavigationView { | |
List(fruits, id: \.self) { fruit in | |
NavigationLink(destination: SecondView(fruit: fruit)) { | |
Text(fruit) | |
} | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
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
import SwiftUI | |
struct SecondView: View { | |
let fruit: String | |
var body: some View { | |
Text(fruit) | |
} | |
} | |
struct SecondView_Previews: PreviewProvider { | |
static var previews: some View { | |
SecondView(fruit: "Apple") | |
} | |
} |