swiftui - SwiftUI 中的 GeometryReader 和 GeometryProxy 有什么区别?

标签 swiftui

按照苹果的说法,

GeometryReader
一个容器 View ,将其内容定义为它自己的大小和坐标空间的函数。


几何代理:
用于访问容器 View 的大小和坐标空间(用于 anchor 分辨率)的代理。


我想了解何时使用 GeometryReader 以及何时使用 GeometryProxy?我做了谷歌,但没有看到任何帖子出现在结果中。所以我在这里问一下,以便像我这样的新开发人员可以引用。

最佳答案

GeometryReader

SwiftUI’s GeometryReader allows us to determine the size and coordinates of views as a function of its own size and coordinates.



您可以像这样使用 GeometryReader:
GeometryReader { geometry in
    SomeView()
        .offset(x: geometry.size.width / 2)
}

几何代理

上面代码中的闭包变量 (geometry) 是 GeometryProxy 类型。这个结构体为我们提供了以下信息:
public var size: CGSize { get }
public var safeAreaInsets: EdgeInsets { get }
public func frame(in coordinateSpace: CoordinateSpace) -> CGRect
public subscript<T>(anchor: Anchor<T>) -> T where T : Equatable { get }

基本上 GeometryReader 读取 View (其大小、坐标等)并返回一个 GeometryProxy 结构,您可以从中访问所有信息。

有用的链接:
  • Understanding frames and coordinates inside GeometryReader
  • GeometryReader to the Rescue
  • Anchor preferences in SwiftUI
  • 关于swiftui - SwiftUI 中的 GeometryReader 和 GeometryProxy 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62377847/

    相关文章:

    swift - 增加可点击区域 Datepicker SwiftUI

    ios - 是否可以在 SwiftUI 中对某个路径上的 View 进行动画处理

    SwiftUI 披萨按钮

    swiftui - 阴影不透明度swiftUI

    swiftui - UIViewRepresentable 无法在模态呈现的 SwiftUI View 中工作

    ios - SwiftUI:创建自定义警报

    swift - 如何在Xcode中调试 “precondition failure”?

    swift - 无法将类型 'Int' 的值转换为预期的参数类型 'Angle' 。 Xcode 11、Mac 10.15、SwiftUI

    swift - 我可以在 SwiftUI 中使用颜色文字吗

    ios - 如何将 ContextMenu 与 NavigationLink 一起使用?