我试图Text()
仅在视图的左侧和右侧添加填充。理想情况下,我想将其宽度设置为等于设备的宽度减去我定义的常数。
例如:
Text("My text view here")
.frame(width: device.width - 16)
在SwiftUI中执行此操作的正确方法是什么?我是否以错误的方式处理此问题?
GeometryReader
是为您提供有关父级的所有信息的类型 view
所以你可以这样使用GeometryReader
:
var body: some View {
GeometryReader { geometry in
Text("My text view here")
.frame(width: geometry.size.width - 16)
.background(Color.red) // This is just to see how it looks like
}
}
您可以直接从设备获取它:
var body: some View {
Text("My text view here")
.frame(width: UIScreen.main.bounds.width - 16)
.background(Color.red) // This is just to see how it looks like
}
请注意,设备宽度是物理宽度,不会随旋转而更新。另外,我还没有尝试过看看自己,但是我已经阅读了UIScreen在SplitView上遇到问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句