1

我是 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")
        }
    }
}
4

1 回答 1

4

我假设你想要这个(用 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")
        }
    }
}
于 2020-09-28T14:28:24.470 回答