【问题标题】:Where is the 'Origin' of a View in SwiftUISwiftUI 中视图的“起源”在哪里
【发布时间】:2020-10-25 11:28:41
【问题描述】:

我在玩 .position(x:y:)CoordinateSpace.global 时遇到了一些让我感到困惑的事情。

我试图确定 ZStack 在全局坐标空间中的原点坐标。但是,当我在这些坐标上放置一个点时,它并没有与 ZStack 的左上角对齐。

这是我使用的代码:

struct Test: View {    
    var body: some View {
        ZStack {
            Image(systemName: "circle.fill")
                .resizable()
                .frame(width: 5, height: 5)
                .foregroundColor(.red)
                .position(x: 177, y: 423)  // This is from 'frame.origin.x' and 'frame.origin.y'
            
            ZStack {  // Trying to determine this ZStack's coordinates in the global coordinate space
                GeometryReader { geometry -> AnyView in  // Used to retrieve the coordinates using `geometry` and then returning a Text so I can see the coordinates on screen
                    let frame = geometry.frame(in: CoordinateSpace.global)
                    return AnyView(Text("\(frame.origin.x), \(frame.origin.y)").fixedSize(horizontal: false, vertical: true))
                }
            }
            .frame(width: 60, height: 60)
        }
    }
}

这就是圆点出现的地方:

有谁知道它为什么出现在应该出现在 ZStack 左上角的那个奇怪的地方?我以为原点应该在视图的左上角?

【问题讨论】:

  • 不清楚你想达到什么目的?你会详细说明吗?您要放置哪个视图和位置。
  • @Asperi 这样更好吗?我试图确定 ZStack 的起源

标签: ios swift layout swiftui frame


【解决方案1】:

您在全局坐标空间中通过几何读取器计算帧,但图像放置在外部 ZStack 坐标空间中,这就是错位的原因。

为了使其按预期工作(接受用于测试目的的硬编码坐标),坐标应在一个坐标空间中生成。

这是一个解决方案

var body: some View {
    ZStack {
        Image(systemName: "circle.fill")
            .resizable()
            .frame(width: 5, height: 5)
            .foregroundColor(.red)
            .position(x: 177, y: 379)  // This is from 'frame.origin.x' and 'frame.origin.y'

        ZStack {
            GeometryReader { geometry -> AnyView in
                let frame = geometry.frame(in: .named("test"))               // << here !!
                return AnyView(Text("\(frame.origin.x), \(frame.origin.y)")
                    .fixedSize(horizontal: false, vertical: true))
            }
        }
        .frame(width: 60, height: 60)
    }.coordinateSpace(name: "test")       // << here !!
}

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多