目标是将动态内容传递到单个模式中,就像它是详细视图一样:
import SwiftUI
struct Item {
let number: String
let id = UUID()
}
class ItemSet: ObservableObject {
@Published var collection: [Item]
init() {
self.collection = []
for index in 1...100 {
self.collection.append(Item(number: "\(index)"))
}
}
}
struct ContentView: View {
@ObservedObject var items: ItemSet
@State private var selectedItem: Item?
@State private var showingFull = false
init() {
self.items = ItemSet()
self.selectedItem = nil
}
var columns = [
GridItem(.adaptive(minimum: 150), spacing: 5.0)
]
var body: some View {
ScrollView {
LazyVGrid(columns: columns) {
ForEach(items.collection, id: \.id) {item in
Text(item.number)
.frame(height: 100)
.onTapGesture {
self.selectedItem = item
self.showingFull = true
}
.sheet(isPresented: $showingFull) {
if let item = selectedItem {
Text(item.number)
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
出于某种原因,第一次点击一个单元格时,模态为空,好像状态在呈现模态内容之前未更新,但是此后的任何时候都可以正常工作。我是否遗漏了明显的东西,还是应该申请雷达? 最佳答案
这是多页冲突,因为您将同一张工作表附加到ForEach
中的每个单元格上并具有绑定到单个状态的功能,因此单击时,它们都立即被激活。解决方案是将工作表移出ForEach
这是已更正的部分。经过Xcode 12 / iOS 14测试
var body: some View {
ScrollView {
LazyVGrid(columns: columns) {
ForEach(items.collection, id: \.id) {item in
Text(item.number)
.frame(height: 100)
.onTapGesture {
self.selectedItem = item
self.showingFull = true
}
}
}
}
.sheet(isPresented: $showingFull) { // << here !!
if let item = selectedItem {
Text(item.number)
}
}
}
关于ios - SwiftUI:仅在第一次尝试时打开带有动态内容的模式表失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63570189/