如何解决SwiftUI:使用全局帧信息定位视图并设置为全屏动画?
我正在尝试熟悉 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)
]
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))
}
}
最外面的几何代理给出了这个尺寸日志:
cellSide:341.5。 cellSide * 列:1366.0,geoProxy.size.width: 1366.0
这是渲染出来的:
例如,当我点击单元格 1 时,会记录以下内容:
局部框架:(0.0,0.0,341.0,341.0),globalFrame: (0.25,testCSpace: (0.25,341.0) on tap cell info: CellInfo(cellId: "Cell 1",341.0))
当点击“Cell 6”时,这是新渲染的屏幕的样子:
因此,鉴于此代码:
- 如何使(白色)叠加视图的框架与我点击的单元格视图的框架相匹配?宽度和高度看起来没问题,但位置是关闭的。 (我做错了什么?)
- 如何将白色视图放置在轻按单元格的正上方后将其设置为全屏动画?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。