[英]How to replace the current view in SwiftUI?
I am developing an app with SwiftUI.我正在使用 SwiftUI 开发应用程序。
I have a NavigationView and I have buttons on the navigation bar.我有一个 NavigationView,并且导航栏上有按钮。 I want to replace the current view (which is a result of a TabView selection) with another one.
我想用另一个替换当前视图(这是 TabView 选择的结果)。
Basically, when the user clicks "Edit" button, I want to replace the view with another view to make the edition and when the user is done, the previous view is restored by clicking on a "Done" button.基本上,当用户单击“编辑”按钮时,我想用另一个视图替换视图以进行编辑,当用户完成时,通过单击“完成”按钮恢复以前的视图。
I could just use a variable to dynamically choose which view is displayed on the current tab view, but I feel like this isn't the "right way to do" in SwiftUI.我可以只使用一个变量来动态选择在当前选项卡视图上显示哪个视图,但我觉得这不是 SwiftUI 中的“正确方法”。 And this way I could not apply any transition visual effect.
这样我就无法应用任何过渡视觉效果。
Some code samples to explain what I am looking for.一些代码示例来解释我在寻找什么。
private extension ContentView {
@ViewBuilder
var navigationBarLeadingItems: some View {
if tabSelection == 3 {
Button(action: {
print("Edit pressed")
// Here I want to replace the tabSelection 3 view by another view temporarly and update the navigation bar items
}) {
Text("Edit")
}
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
TabView(selection: $tabSelection) {
ContactPage()
.tabItem {
Text("1")
}
.tag(1)
Text("Chats")
.tabItem() {
Text("2")
}
.tag(2)
SettingsView()
.tabItem {
Text("3")
}
.tag(3)
}.navigationBarItems(leading: navigationBarLeadingItems)
}
}
}
Thank you谢谢
EDIT编辑
I have a working version where I simply update a toggle variable in my button action that makes my view display one or another thing, it is working but I cannot apply any animation effect on it, and it doesn't look "right" in SwiftUI, I guess there is something better that I do not know.我有一个工作版本,我只需在按钮操作中更新一个切换变量,使我的视图显示一件或另一件事,它正在工作,但我无法对其应用任何 animation 效果,并且它在 SwiftUI 中看起来不“正确” ,我想有更好的东西我不知道。
If you just want to add animations you can try:如果您只想添加动画,可以尝试:
struct ContentView: View {
...
@State var showEditView = false
var body: some View {
NavigationView {
TabView(selection: $tabSelection) {
...
view3
.tabItem {
Text("3")
}
.tag(3)
}
.navigationBarItems(leading: navigationBarLeadingItems)
}
}
}
private extension ContentView {
var view3: some View {
VStack {
if showEditView {
FormView()
.background(Color.red)
.transition(.slide)
} else {
Text("View 3")
.background(Color.blue)
.transition(.slide)
}
}
}
}
struct FormView: View {
var body: some View {
Form {
Text("test")
}
}
}
A possible alternative is to use a ViewRouter : How To Navigate Between Views In SwiftUI By Using An @EnvironmentObject .一种可能的替代方法是使用ViewRouter : How To Navigate between Views In SwiftUI By Using An @EnvironmentObject 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.