我在 ScrollView 中创建了一个 LazyVGrid(垂直和水平)。
虽然布局按我的预期工作,但当用户与窗口交互时(例如:通过更改其大小),按钮有时不会对鼠标单击做出反应。
import SwiftUI
struct Cell: Identifiable {
var id: UUID = UUID()
var i: Int = 0
init(i: Int) {
self.i = i
}
}
struct ContentView: View {
var columns: [GridItem] = [GridItem](repeating: GridItem(.fixed(40), spacing: 5), count: 60)
var cells: [Cell] = []
init() {
cells.removeAll()
for i in 0..<180 {
cells.append(Cell(i:i))
}
}
var body: some View {
ScrollView([.horizontal, .vertical]) {
LazyVGrid(columns: columns, spacing: 5) {
ForEach(cells) { cell in
ButtonView(cell: cell)
}
}
}
}
}
struct ButtonView: View {
var cell: Cell
@State var popOver: Bool = false
var body: some View {
Button {
popOver.toggle()
} label: {
Text("\(cell.i)")
}
.popover(isPresented: $popOver, content: {
Text("Information line of button \(cell.i)").padding()
})
}
}
#Preview {
ContentView()
}
这个视频 展示了我面临的问题。
如您所见,代码创建了一个按钮网格。每次我单击按钮时都会出现一个弹出窗口。运行应用程序后,弹出窗口有时不会出现,有时会出现在移动的位置。
我在带有宽屏显示器和 Xcode 的 mac mini 上运行:15.3 和 macOS:14.2
对于所有可能感兴趣的人:
我发现如果我将 ScrollView 放置在之前带有另一个视图的视图容器(例如:VStack)中,那么一切都会正常工作。
下面我发布了完整的代码,它可以工作(至少在我的系统中):
import SwiftUI
struct Cell: Identifiable {
var id: UUID = UUID()
var i: Int = 0
init(i: Int) {
self.i = i
}
}
struct ContentView: View {
var columns: [GridItem] = [GridItem](repeating: GridItem(.fixed(40), spacing: 5), count: 60)
var cells: [Cell] = []
init() {
for i in 0..<180 {
cells.append(Cell(i:i))
}
}
var body: some View {
VStack {
Text("")
ScrollView([.horizontal, .vertical]) {
LazyVGrid(columns: columns, spacing: 5) {
ForEach(cells) { cell in
ButtonView(cell: cell)
}
}
}
}
}
}
struct ButtonView: View {
var cell: Cell
@State var popOver: Bool = false
var body: some View {
Button {
popOver.toggle()
} label: {
Text("\(cell.i)")
}
.popover(isPresented: $popOver, content: {
Text("Information line of button \(cell.i)").padding()
})
}
}
#Preview {
ContentView()
}