[英]How to navigate from one view to another in Swift UI on a click of button
I want to push from one view to another in SwiftUI on a click of button.我想通过单击按钮在 SwiftUI 中从一个视图推送到另一个视图。 Likewise we navigate from one controller to another controller in storyboard.
同样,我们在 storyboard 中从一个 controller 导航到另一个 controller。
But in SwiftUI how to achieve this.但是在 SwiftUI 如何实现这一点。
You can solve it by using NavigationLink您可以使用 NavigationLink 解决它
What is NavigationLink?什么是导航链接?
NavigationLink: Creates a button on the right hand side of each cell and triggers presentation to the detail view NavigationLink:在每个单元格的右侧创建一个按钮并触发显示到详细视图
Apple Link: https://developer.apple.com/documentation/swiftui/navigationlink苹果链接: https://developer.apple.com/documentation/swiftui/navigationlink
Sample Projects示例项目
Apple https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation苹果https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation
Github https://github.com/appbrewery/H4X0R-News-iOS13-SwiftUI-Completed Github https://github.com/appbrewery/H4X0R-News-iOS13-SwiftUI-Completed
How to Implement:如何实施:
import SwiftUI
struct LandmarkList: View {
var body: some View {
NavigationView {
List(landmarkData) { landmark in
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
*Note: "LandmarkDetail" is your destination view. *注意:“LandmarkDetail”是您的目标视图。
You can also download the sample project from apple (link mentioned above) to understand it clearly你也可以从苹果下载示例项目(上面提到的链接)以清楚地理解它
There are two ways to achieve that.有两种方法可以实现这一目标。
The first one is with "isActive" binding.第一个是“isActive”绑定。
struct ViewA: View {
@State private var isActive = false
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: NextView(),
isActive: $isActive) {
Button(action: {
self.isActive = true
}) {
Text("Push Next View")
}
}
}
}
}
}
You place the view which you want to push in the NavigationLink's destination.您将要推送的视图放置在 NavigationLink 的目的地中。 The second way is again with NavigationLink, but using "tag" and "selection".
第二种方法是再次使用 NavigationLink,但使用“标签”和“选择”。 There the navigation is activated when the selection matches the tag.
There the navigation is activated when the selection matches the tag.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.