4

考虑到下面的代码,我希望我的 TabView 在显示我的选项卡视图时显示随机计算的图像,但事实并非如此。它将始终在索引 0 处显示第一张图像。如果我在 TabView 初始化程序(即.constant(n))中对选择进行硬编码,那么它将正确显示所选图像。我已经为此提交了一份雷达(FB7844985),但想检查一下我没有遗漏一些明显的东西吗?

struct ContentView: View {
    let assets: [String] = (1...32).map { "preview_\($0)"}
    
    @State private var selection: Int = 0
    @State private var isPresented: Bool = false
    var body: some View {
        VStack {
            Button("Random element") {
                selection = Int.random(in: 1...32)
                isPresented = true
            }
        }
        .sheet(isPresented: $isPresented) {
            SlideshowView(selection: $selection, assets: assets)
        }
    }
}

struct SlideshowView: View {
    @Binding var selection: Int
    var assets: [String]
    var body: some View {
        TabView(selection: $selection) {
            ForEach(assets.indices, id: \.self) { index in
                Image(assets[index])
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
        }
        .tabViewStyle(PageTabViewStyle())
        .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
    }
}
4

1 回答 1

5

原因不在于模态(即显示在工作表中),而是因为TabView没有读取初始(!)选择(这绝对是一个 SwiftUI 错误)

这是解决方法(在复制代码上使用 Xcode12 / iOS 14 测试)

演示

struct SlideshowView: View {
    @Binding var selection: Int
    var assets: [String]
    var body: some View {
        TabView(selection: $selection) {
            ForEach(assets.indices, id: \.self) { index in
                Image(assets[index])
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
        }
        .tabViewStyle(PageTabViewStyle())
        .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
        .onAppear {
            // WORKAROUND: simulate change of selection on appear !!
            let value = selection
            selection = -1
            DispatchQueue.main.async {
                selection = value
            }
        }
    }
}
于 2020-07-03T13:16:09.300 回答