如何在 SwiftUI 中使用按钮导航回一个视图
Posted
技术标签:
【中文标题】如何在 SwiftUI 中使用按钮导航回一个视图【英文标题】:How can I navigate one view back with a button in SwiftUI 【发布时间】:2020-07-03 18:35:42 【问题描述】:我有一个ContentView
和一个TabView
。当我在AddItemView
中添加一个项目并按下保存按钮时,我想打开MyDataView
。我已经尝试了NavigationLink
,但这显示了一个奇怪的嵌套NavigationView
。按下保存按钮后,我该怎么做才能显示MyDataView
?
struct ContentView: View
var body: some View
TabView()
MyDataView()
.tabItem
Image(systemName: "chevron.down.circle.fill")
Text("My Data")
.tag(1)
AddItemView()
.tabItem
Image(systemName: "chevron.up.circle")
Text("Add Item")
.tag(2)
struct AddItemView: View
var body: some View
NavigationView
Form
// My Form with textfields
Button(action:
//save
)
Text("Add")
.navigationBarTitle(Text("Add Item"))
struct MyDataView: View
var body: some View
NavigationView
List(["foo", "bar"], id: \.self) item in
Text(item)
.navigationBarTitle(Text("My Data"))
´´´
【问题讨论】:
【参考方案1】:这是一个可能的解决方案。使用 Xcode 12 测试。
仅修改组件:
struct DDContentView: View
@State private var selection: Int = 1 // << here
var body: some View
TabView(selection: $selection) // << here
MyDataView()
.tabItem
Image(systemName: "chevron.down.circle.fill")
Text("My Data")
.tag(1)
AddItemView()
self.selection = 1 // in callback change selection
.tabItem
Image(systemName: "chevron.up.circle")
Text("Add Item")
.tag(2)
struct AddItemView: View
var completion: () -> () // << here !!
var body: some View
NavigationView
Form
// My Form with textfields
Button(action:
//save
self.completion() // << callback !!
)
Text("Add")
.navigationBarTitle(Text("Add Item"))
【讨论】:
【参考方案2】:您可以创建一个 ObservableObject 并使用它来跟踪 TabView 中选定的选项卡,然后您只需将其传递给您想要切换选项卡的所有视图。 像这样:
class AppState: ObservableObject
@Published var currentTab: Tab = .data
enum Tab
case data, item
struct ContentView: View
@ObservedObject var appState = AppState()
@State var currentTab: Tab
var body: some View
TabView(selection: $appState.currentTab)
MyDataView()
.tabItem
Image(systemName: "chevron.down.circle.fill")
Text("My Data")
.tag(Tab.data)
AddItemView(appState: appState)
.tabItem
Image(systemName: "chevron.up.circle")
Text("Add Item")
.tag(Tab.item)
struct AddItemView: View
@ObservedObject var appState: AppState
var body: some View
NavigationView
Form
// My Form with textfields
Button(action:
appState.currentTab = .data
)
Text("Add")
.navigationBarTitle(Text("Add Item"))
struct MyDataView: View
var body: some View
NavigationView
List(["foo", "bar"], id: \.self) item in
Text(item)
.navigationBarTitle(Text("My Data"))
【讨论】:
以上是关于如何在 SwiftUI 中使用按钮导航回一个视图的主要内容,如果未能解决你的问题,请参考以下文章