我有一个带有两个tabItems的TabView(它们都是NavigationViews)。我想在每个选项卡上都有一个NavigationBarItem,它将在TabView顶部推一张纸。但是,每当我显示工作表时,似乎都会将我的选择设置为0。
import SwiftUI
struct SheetTest: View {
@State var selection = 0
@State var showSheet = false
var body: some View {
TabView(selection: $selection) {
NavigationView {
Text("Tab 1")
.navigationBarItems(trailing: button)
}.navigationViewStyle(StackNavigationViewStyle())
.tabItem({
Image(systemName: "1.circle")
Text("Tab 1")
})
NavigationView {
Text("Tab 2")
.navigationBarItems(trailing: button)
}.navigationViewStyle(StackNavigationViewStyle())
.tabItem({
Image(systemName: "2.circle")
Text("Tab 2")
})
}
.sheet(isPresented: $showSheet) {
Text("Sheet")
}
}
var button: some View {
return Button(action: {
showSheet = true
}, label: {
Text("button")
})
}
}
struct SheetTest_Previews: PreviewProvider {
static var previews: some View {
SheetTest()
}
}
答案 0 :(得分:1)
您需要为每个项目添加标签:
/* ... */
.tabItem({
Image(systemName: "1.circle")
Text("Tab 1")
})
.tag(0) // <-- Here
并且:
/* ... */
.tabItem({
Image(systemName: "2.circle")
Text("Tab 2")
})
.tag(1) // <-- And here
答案 1 :(得分:1)
您需要标记标签项,以便切换标签将存储选择。
此处是固定变体。经过Xcode 12 / iOS 14的测试
struct SheetTest: View {
@State var selection = 0
@State var showSheet = false
var body: some View {
TabView(selection: $selection) {
NavigationView {
Text("Tab 1")
.navigationBarItems(trailing: button)
}.navigationViewStyle(StackNavigationViewStyle())
.tabItem({
Image(systemName: "1.circle")
Text("Tab 1")
}).tag(0) // << here !!
NavigationView {
Text("Tab 2")
.navigationBarItems(trailing: button)
}.navigationViewStyle(StackNavigationViewStyle())
.tabItem({
Image(systemName: "2.circle")
Text("Tab 2")
}).tag(1) // << and here !!
}
.sheet(isPresented: $showSheet) {
Text("Sheet")
}
}
var button: some View {
return Button(action: {
showSheet = true
}, label: {
Text("button")
})
}
}
答案 2 :(得分:0)
对我来说我有 @State var tabSelection: Double = 0.0
本来应该是@State var tabSelection = 0
修复:删除 Double
的类型并确保设置了 .tag(number)