英文:
Is there a better way to use repeated Spacers in Swift UI?
问题
我想在屏幕顶部的1/3处显示一个视图。为了实现这个目标,我这样操作:
var body: some View {
VStack{
Spacer()
Text("我喜欢 Chipotle")
Spacer()
Spacer()
}
}
尽管这对于较小的示例有效,但我想知道是否有一种更声明式的方法来实现这一目标,以便例如我想将一个视图放在屏幕顶部的1/6处?我考虑到了 flex 布局,其中您可以设置特定子元素的 flex 值以使它们占据不同的百分比。
英文:
I want to display a View in the top 1/3 of the screen. In order to do so, I manipulate it as so:
var body: some View {
VStack{
Spacer()
Text("I like chipotle")
Spacer()
Spacer()
}
}
While that works for smaller examples, I wonder if there is a more declarative way to do this so if I for example want to put a view in the top 1/6 of a screen? I think about flex box where you can set the flex value of specific children to make them take up different percentages.
答案1
得分: 1
或许你的意思是这样的:
struct ContentView: View {
let partOfScreen: CGFloat = 1/3
var body: some View {
GeometryReader { geo in
VStack(spacing: 0) {
Text("我喜欢 Chipotle")
.padding(.top, geo.size.height * partOfScreen)
Spacer(minLength: 0)
}
}
.ignoresSafeArea(.all) // 如果需要整个屏幕区域
}
}
英文:
Maybe you mean something like this:
struct ContentView: View {
let partOfScreen: CGFloat = 1/3
var body: some View {
GeometryReader { geo in
VStack(spacing: 0) {
Text("I like chipotle")
.padding(.top, geo.size.height * partOfScreen)
Spacer(minLength: 0)
}
}
}
}
You can add .ignoresSafeArea(.all)
on GeometryReader
if the entire screen area is needed
答案2
得分: 0
无需使用任何Spacer
,您可以直接使用GeometryReader
将视图的大小相对于其父视图进行分配:
GeometryReader { proxy in
Text("我喜欢 Chipotle")
.frame(height: proxy.size.height/3.rounded())
}
}
💡 快速提示
> 始终尝试round
位置和大小值。否则,它会严重影响渲染引擎以呈现小数像素,可能会导致卡顿和丢帧。
英文:
No need for any Spacer
You can directly assign the size to a view relative to its parent using the GeometryReader
:
GeometryReader { proxy in
Text("I like Chipotle")
.frame(height: proxy.size.height/3.rounded())
}
}
💡 Quick Tip
> Always try to round
position and size values. Otherwise, it will heavily impact the render engine to render fractional pixels and you may experience lags and drop frames.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论