swift 如何将TabView按钮移到旁边

vcirk6k6  于 2023-04-10  发布在  Swift
关注(0)|答案(1)|浏览(131)

我有一个现有的应用程序,其主界面为TabView。例如:

struct MainView: View {
    var body: some View {
        TabView {
            RecentView()
                .tabItem {
                    Text("One")
                }
            RecentView()
                .tabItem {
                    Text("Two")
                }
            RecentView()
                .tabItem {
                    Text("Three")
                }
        }
    }
}

现在他们想添加一个选项卡项目,但在右上角关闭它,如下所示:

这怎么可能呢?

zf9nrax1

zf9nrax11#

这并不漂亮,但这是总体思路。关键是.tag()你的视图,这样你就可以用@State var引用它们。然后你使用什么来触发更改并不重要。它可以是用户发起的或编程的。

struct TabViewSideButton: View {
    
    // This trackes what view to show.
    @State private var tabSelection = 1
    
    var body: some View {
        ZStack(alignment: .top) {
            TabView(selection: $tabSelection) {
                RecentView(text: "One")
                    .tag(1) // tags go on each view.
                RecentView(text: "Two")
                    .tag(2)
                RecentView(text: "Three")
                    .tag(3)
            }
            HStack {
                // Set your variable whereever
                Picker("", selection: $tabSelection) {
                    ForEach([1,2], id: \.self) { choice in
                        Text(spellout.string(from: choice as NSNumber) ?? "")
                    }
                }
                .pickerStyle(.segmented)
                
            }
            .frame(width: 200)
            .padding()
            
            HStack {
                Spacer()
                Button {
                    // Set your variable whereever
                    tabSelection = 3
                } label: {
                    Text("Three")
                }
                
            }
            .padding()
        }
        
    }
    
    var spellout: NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return formatter
    }
}

相关问题