考虑到下面的代码,我希望我的 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))
}
}