几何学和.Frame的对齐
我使用的是geometryReader()和.frame()来显示它们的可比性并播放其宽度。 但是,当宽度小于最小值时,包裹在geometryReader()中的对象没有中心对齐。 请参阅随附的GIF进行演示。
你能帮我对齐吗?
理想:
struct ExampleView: View {
@State private var width: CGFloat = 50
var body: some View {
VStack {
SubView()
.frame(width: self.width, height: 120)
.border(Color.blue, width: 2)
Text("Offered Width is \(Int(width))")
Slider(value: $width, in: 0...200, step: 5)
}
}
}
struct SubView: View {
var body: some View {
GeometryReader { geometry in
Rectangle()
.fill(Color.yellow.opacity(0.6))
.frame(width: max(geometry.size.width, 120), height: max(geometry.size.height, 120))
}
}
}
I'm using GeometryReader() and .frame() to show their comparability and playing with their width.
However the object wrapped in GeometryReader() doesn't have center alignment when width is less than minimum.
Please refer to attached gifs for demo.
Could you please help me with alignment?
Ideal:
struct ExampleView: View {
@State private var width: CGFloat = 50
var body: some View {
VStack {
SubView()
.frame(width: self.width, height: 120)
.border(Color.blue, width: 2)
Text("Offered Width is \(Int(width))")
Slider(value: $width, in: 0...200, step: 5)
}
}
}
struct SubView: View {
var body: some View {
GeometryReader { geometry in
Rectangle()
.fill(Color.yellow.opacity(0.6))
.frame(width: max(geometry.size.width, 120), height: max(geometry.size.height, 120))
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那是因为
几何读程序
不关心孩子。您必须通过添加
.position
修改器或.offset
来手动定位矩形
。.position
将相对于父中心的矩形框架的原点。.offset
不会更改框架,而是更改渲染(像cgaffineTransform一样工作,并带有翻译)。
您的
矩形
的以下修饰符将以视觉上产生相同的结果(尽管在引擎盖下不同):或
注意您的矩形框架超过了其父级的界限。我建议避免这种情况,因为它将在屏幕上造成各种困难。
您可以以相反的方式构建它(除非您的实际目标是仅了解
geometryReader
有效):在此示例中而内部矩形只需在滑块上设置任何宽度。它还不再需要
deegomeReader
。它的外观和行为相同,但没有任何视图超过其父母的界限。That's because
GeometryReader
doesn't center its children.You have to manually position the
Rectangle
by adding either a.position
modifier or a.offset
..position
will move the origin of the rectangle's frame relative to the parent's center..offset
will not change the frame, but rather change the rendering (working like aCGAffineTransform
with translation).The following modifiers to your
Rectangle
will yield the same results visually (though different under the hood):or
Note that your rectangle's frame exceeds the bounds of its parent. I'd suggest to avoid that because it will cause all sorts of difficulties laying out other UI elements on the screen.
You could build it the other way around (unless your practical goal is to just understand how
GeometryReader
works):In this example the
SubView
has a yellow fill and a minimal frame width while the inner rectangle just takes whatever width is set on the slider. It also doesn't need aGeometryReader
anymore. It looks and behaves the same but none of the views exceeds its parent's bounds anymore.