我是SwiftUI的新手,我试图构建一个标签栏,其中包含一个标签,该标签将返回模式(工作表)但不返回视图。经过尝试,我发现有时它可以工作,但有时却不行。我想在用户取消模式后将上一个选项卡式项目作为所选选项卡。但是我找不到错误所在。有人向我解释我的代码有什么问题吗?
import SwiftUI
struct ContentView: View {
@State var isPresenting = false
@State private var selectedItem = 1
@State private var oldSelectedItem = 1
var body: some View {
TabView(selection: $selectedItem){
Text("1")
.tabItem {
Image(systemName: "house")
}.tag(1)
.onAppear {
self.oldSelectedItem = self.selectedItem
}
Text("") // I want this to display the sheet.
.tabItem { Image(systemName: "plus.circle") }
.tag(2)
.onAppear {
self.isPresenting = true
self.selectedItem = self.oldSelectedItem
}
Text("3")
.tabItem {
Image(systemName: "calendar")
}.tag(3)
.onAppear {
self.oldSelectedItem = self.selectedItem
}
}
.sheet(isPresented: $isPresenting) {
testSheet
}
.accentColor(Color.orange)
}
var testSheet : some View {
VStack{
Text("testing")
}
}
}
答案 0 :(得分:0)
我想你想要这个(经过Xcode 12 / iOS 14测试)
struct ContentView: View {
@State var isPresenting = false
@State private var selectedItem = 1
@State private var oldSelectedItem = 1
var body: some View {
TabView(selection: $selectedItem){
Text("1")
.tabItem {
Image(systemName: "house")
}.tag(1)
Text("") // I want this to display the sheet.
.tabItem { Image(systemName: "plus.circle") }
.tag(2)
Text("3")
.tabItem {
Image(systemName: "calendar")
}.tag(3)
}
// .onReceive(Just(selectedItem)) // SwiftUI 1.0 - import Combine for this
.onChange(of: selectedItem) { // SwiftUI 2.0 track changes
if 2 == selectedItem {
self.isPresenting = true
} else {
self.oldSelectedItem = $0
}
}
.sheet(isPresented: $isPresenting, onDismiss: {
self.selectedItem = self.oldSelectedItem
}) {
testSheet
}
.accentColor(Color.orange)
}
var testSheet : some View {
VStack{
Text("testing")
}
}
}