#6 GeometryReader

GeometryReady 很费性能, 所以能不用就不用

功能

GeometryReader 不是布局容器,而是一个只读测量盒 :它把父视图分配给自己的实际尺寸与坐标 通过 GeometryProxy 实时向下注入,让子视图能够:

  • 按百分比计算帧大小
  • 实现屏幕驱动动画(3D 旋转、视差、滑动缩放等)
  • 获取全局坐标,用于拖拽、碰撞检测、滚动联动

API

swift 复制代码
GeometryReader { proxy in
    // 子视图
}

proxy 提供:

  • sizeCGSize ------ Reader 得到的确定尺寸

  • frame(in:) ------ 在不同坐标系里的 frame:

    • .local:自身坐标系
    • .global:屏幕原点
    • .named(id):自定义坐标空间(配合 .coordinateSpace(name:) 使用)
  • safeAreaInsets ------ 当前 Safe Area 插值

示例

swift 复制代码
struct GeometryReaderBootcamp: View {
    var body: some View {
        // GeometryReady 很费性能, 所以能不用就不用
        //        GeometryReader { geometry in
        //            HStack(spacing: 0) {
        //                Rectangle()
        //                    .fill(.red)
        //                    .frame(width: geometry.size.width * 0.66)
        //                Rectangle().fill(.blue)
        //            }
        //            .ignoresSafeArea()
        //        }
        
        ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(0..<20) { index in
                    GeometryReader { geometry in
                        RoundedRectangle(cornerRadius: 16)
                            .rotation3DEffect(
                                Angle(degrees: getPercentage(geometry: geometry) * 40),
                                axis: (x: 0, y: 1.0, z: 0.0))
                    }
                    .frame(width: 320, height: 240)
                    .padding()
                }
            }
        }
    }
        
    private func getPercentage(geometry: GeometryProxy) -> Double {
        let maxDistance = UIScreen.main.bounds.width / 2
        let currentX = geometry.frame(in: .global).midX
        
        return Double(1 - (currentX / maxDistance))
    }
}

性能与最佳实践

  1. 避免深层嵌套:布局阶段每帧都会重新调用闭包。
  2. 仅需尺寸时,优先使用 .frame(maxWidth: .infinity, maxHeight: .infinity) + 背景图层,代替嵌套 Reader。
  3. 需要全局坐标再 frame(in: .global),不要一上来就放在最外层。
  4. ScrollViewLazyVStack 联用时,把 Reader 放在叶子节点,减少重算范围。
  5. 若只关心 Safe Area 插值,可用 .padding(.safeArea) 替代 Reader。

小结

GeometryReader 是 SwiftUI 的"尺子"------不绘制、只测量

合理用它可实现百分比布局、视差动画、滑动联动等高级效果;

但牢记:能靠固有布局解决的,就不要让尺子上场。

相关推荐
T1an-12 小时前
最右IOS岗一面
ios
坏小虎4 小时前
Expo 快速创建 Android/iOS 应用开发指南
android·ios·rn·expo
光影少年5 小时前
Android和iOS原生开发的基础知识对RN开发的重要性,RN打包发布时原生端需要做哪些配置?
android·前端·react native·react.js·ios
北京自在科技6 小时前
Find My 修复定位 BUG,AirTag 安全再升级
ios·findmy·airtag
Digitally6 小时前
如何不用 USB 线将 iPhone 照片传到电脑?
ios·电脑·iphone
Sim148019 小时前
iPhone将内置本地大模型,手机端AI实现0 token成本时代来临?
人工智能·ios·智能手机·iphone
Digitally21 小时前
如何将 iPad 上的照片传输到 U 盘(4 种解决方案)
ios·ipad
报错小能手1 天前
ios开发方向——swift并发进阶核心 @MainActor 与 DispatchQueue.main 解析
开发语言·ios·swift
LcGero1 天前
Cocos Creator 业务与原生通信详解
android·ios·cocos creator·游戏开发·jsb
ii_best1 天前
lua语言开发脚本基础、mql命令库开发、安卓/ios基础开发教程,按键精灵新手工具
android·ios·自动化·编辑器