新しいビューをNavigationViewにプッシュする方法
How to push a new view onto a NavigationView
//----------------------------------- struct DetailView: View { var body: some View { Text("This is the detail view") } } //----------------------------------- struct ContentView: View { var body: some View { NavigationView { VStack { NavigationLink(destination: DetailView()) { Text("Show Detail View") }.navigationBarTitle("Navigation") } } } }//-----------------------------------
リスト行がタップされたときに新しいビューをプッシュする方法
How to push a new view when a list row is tapped
//----------------------------------- struct RestaurantView: View { var restaurant: Restaurant var body: some View { Text("Come and eat at \(restaurant.name)") .font(.largeTitle) } } //----------------------------------- struct Restaurant: Identifiable { var id = UUID() var name: String } //----------------------------------- struct RestaurantRow: View { var restaurant: Restaurant var body: some View { Text(restaurant.name) } } //----------------------------------- struct ContentView: View { var body: some View { let first = Restaurant(name: "Joe's Original") let restaurants = [first] return NavigationView { List(restaurants) { restaurant in NavigationLink(destination: RestaurantView(restaurant: restaurant)) { RestaurantRow(restaurant: restaurant) } }.navigationBarTitle("Select a restaurant") } } } //-----------------------------------
シートを使用して新しいビューを表示する方法
How to present a new view using sheets
//----------------------------------- struct DetailView: View { var body: some View { Text("Detail") } } //----------------------------------- struct ContentView: View { @State var showingDetail = false var body: some View { Button(action: { self.showingDetail.toggle() }) { Text("Show Detail") }.sheet(isPresented: $showingDetail) { DetailView() } } } //-----------------------------------
ビューを却下する方法
How to make a view dismiss itself
Swiftでこれを解決する方法は2つあります。両方を紹介して、どちらがニーズに合っているかを判断できるようにします。
①環境プロパティ
②バインディングを渡すこと
//----------------------------------- struct DetailView: View { // 方法① //@Environment(\.presentationMode) var presentationMode // 方法② @Binding var isPresented: Bool var body: some View { Text("Detail") Button(action: { // 方法① //self.presentationMode.wrappedValue.dismiss() // 方法② self.isPresented = false }){ Text("Show Detail") } } } //----------------------------------- struct ContentView: View { @State var showingDetail = false var body: some View { Button(action: { self.showingDetail.toggle() }) { Text("Show Detail") }.sheet(isPresented: $showingDetail) { // 方法① //DetailView() // 方法② DetailView(isPresented: self.$showingDetail) } } } //-----------------------------------