官方对 coordinateSpace 的解释是:
Assigns a name to the view’s coordinate space, so other code can operate on dimensions like points and sizes relative to the named space.
我的理解是,用户可以给某个 view 的空间坐标取个名字,然后获取到其他 view 在指定名字空间中的相对坐标。
比如横向排列 3 个圆形。
⭕️⭕️⭕️
计算第 2 个圆形相对于第 3 个圆形的相对坐标。由于第 2 个⭕️在第三个⭕️的左侧,相对坐标的 x 值,应该是负数。
在第 2 个⭕️中,print(proxy.frame(in: .named("circle3")).origin)的输出结果总是正的。
是我对 coordinateSpace 的理解有问题吗?
var body: some View {
HStack(spacing:0) {
Circle()
.fill(.red)
.frame(width: 100, height: 100)
.coordinateSpace(name: "circle1")
GeometryReader{ proxy in
Circle()
.fill(.green)
.frame(width: 100, height: 100)
.coordinateSpace(name: "circle2")
.onTapGesture {
print(proxy.frame(in: .named("circle3")).origin);
}
}
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.coordinateSpace(name: "circle3")
}
.coordinateSpace(name: "stack")
}
看官方说明完全找不到头绪。 https://developer.apple.com/documentation/swiftui/view/coordinatespace(name:)