我正在尝试熟悉 SwiftUI 中的 LazyVGrid、布局和框架/坐标空间,并绘制一个有 4 列的网格,每列是屏幕宽度的 1/4。最重要的是,在单元格点击时,我想在点击的单元格上放置一个视图,并将其动画化为全屏(或我选择的自定义框架)。
我有以下代码:
struct CellInfo {
let cellId:String
let globalFrame:CGRect
}
struct TestView: View {
var columns = [
GridItem(.flexible(), spacing: 0),
GridItem(.flexible(), spacing: 0),
GridItem(.flexible(), spacing: 0),
GridItem(.flexible(), spacing: 0)
]
let items = (1...100).map { "Cell \($0)" }
@State private var cellInfo:CellInfo?
var body: some View {
GeometryReader { geoProxy in
let cellSide = CGFloat(Int(geoProxy.size.width) / columns.count)
let _ = print("cellSide: \(cellSide). cellSide * columns: \(cellSide*CGFloat(columns.count)), geoProxy.size.width: \(geoProxy.size.width)")
ZStack(alignment: .center) {
ScrollView(.vertical) {
LazyVGrid(columns: columns, alignment: .center, spacing: 0) {
ForEach(items, id: \.self) { id in
CellView(testId: id, cellInfo: $cellInfo)
.background(Color(.green))
.frame(width: cellSide, height: cellSide, alignment: .center)
}
}
}
.clipped()
.background(Color(.systemYellow))
.frame(maxWidth: geoProxy.size.width, maxHeight: geoProxy.size.height)
if cellInfo != nil {
Rectangle()
.background(Color(.white))
.frame(width:cellInfo!.globalFrame.size.width, height: cellInfo!.globalFrame.size.height)
.position(x: cellInfo!.globalFrame.origin.x, y: cellInfo!.globalFrame.origin.y)
}
}
.background(Color(.systemBlue))
.frame(maxWidth: geoProxy.size.width, maxHeight: geoProxy.size.height)
}
.background(Color(.systemRed))
.coordinateSpace(name: "testCSpace")
.statusBar(hidden: true)
}
}
struct CellView: View {
@State var testId:String
@Binding var cellInfo:CellInfo?
var body: some View {
GeometryReader { geoProxy in
ZStack {
Rectangle()
.stroke(Color(.systemRed), lineWidth: 1)
.background(Color(.systemOrange))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay(
Text("cell: \(testId)")
)
.onTapGesture {
let testCSpaceFrame = geoProxy.frame(in: .named("testCSpace"))
let localFrame = geoProxy.frame(in: .local)
let globalFrame = geoProxy.frame(in: .global)
print("local frame: \(localFrame), globalFrame: \(globalFrame), testCSpace: \(testCSpaceFrame)")
let info = CellInfo(cellId: testId, globalFrame: globalFrame)
print("on tap cell info: \(info)")
cellInfo = info
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.background(Color(.systemGray))
}
}
最外面的几何代理给出这个大小日志:
细胞侧:341.5。cellSide * 列:1366.0,geoProxy.size.width:1366.0
这是渲染的内容:
例如,当我点击单元格 1 时,会记录以下内容:
local frame: (0.0, 0.0, 341.0, 341.0), globalFrame: (0.25, 0.0, 341.0, 341.0), testCSpace: (0.25, 0.0, 341.0, 341.0) on tap cell info: CellInfo(cellId: "Cell 1", globalFrame: (0.25, 0.0, 341.0, 341.0))
点击“Cell 6”时,新渲染的屏幕如下所示:
因此,鉴于此代码:
- 我怎样才能让(白色)覆盖视图的框架与我点击的单元格视图的框架相匹配?宽度和高度似乎还可以,但位置已关闭。(我究竟做错了什么?)
- 一旦放置在点击的单元格顶部,如何让白色视图动画到全屏?