Chr*_*ris 4 tabview swiftui xcode12
考虑到下面的代码,我希望我的 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))
}
}
Run Code Online (Sandbox Code Playgroud)
原因不在于形式(即在工作表中显示),而在于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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2132 次 |
| 最近记录: |