概要
position设置要注意两个大坑。
1、position(x,y)会设置在父控件的左上角位置。但是这个子控件的开始位置不是子控件的左上角部分,而是子控件的中心原点。
2、设定position后,不是原来的大小,而是占据整个控件。
代码
ZStack{
Rectangle()
.foregroundColor(.blue)
.frame(width: 75, height: 75)
.position(CGPoint(x: 0, y: 0))
Rectangle()
.foregroundColor(.teal)
.frame(width: 50, height: 50)
.position(CGPoint(x: 200, y: 200))
}
.frame(maxWidth: 200, maxHeight: 200)
.background(.yellow)
效果如下图,子控件的中心点落在Position(0,0) 和 Position(200,200)
如果需要调整位置,可以配合GeometryReader精准控制。
ZStack{
GeometryReader { geometry in
Rectangle()
.foregroundColor(.blue)
.frame(width: 75, height: 75)
.position(CGPoint(x: 75/2, y: 75/2))
Rectangle()
.foregroundColor(.teal)
.frame(width: 50, height: 50)
.position(CGPoint(x: geometry.size.width - 50/2, y: geometry.size.width - 50/2))
}
}
.frame(maxWidth: 200, maxHeight: 200)
.background(.yellow)
效果图如下。 position配合GeometryReader精准控制位置。