gpt4 book ai didi

ios - 在 SwiftUI 中让 VStack 填满屏幕宽度

转载 作者:IT王子 更新时间:2023-10-29 05:46:31 25 4
gpt4 key购买 nike

给定这段代码:

import SwiftUI

struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)

Text("Content")
.lineLimit(nil)
.font(.body)

Spacer()
}
.background(Color.red)
}
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif

它的结果是这个界面:

preview

即使标签/文本组件不需要全宽,我怎样才能让 VStack 填满屏幕的宽度?


我发现的一个技巧是在结构中插入一个 HStack,如下所示:

VStack(alignment: .leading) {
HStack {
Spacer()
}
Text("Title")
.font(.title)

Text("Content")
.lineLimit(nil)
.font(.body)

Spacer()
}

产生所需的设计:

desired output

有没有更好的办法?

最佳答案

尝试使用带有以下选项的 .frame 修饰符:

.frame(
minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity,
alignment: .topLeading
)
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Hello World")
.font(.title)
Text("Another")
.font(.body)
Spacer()
}
.frame(
minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity,
alignment: .topLeading
)
.background(Color.red)
}
}

这被描述为一个灵活的框架 ( see the documentation ),它将拉伸(stretch)以填满整个屏幕,当它有额外的空间时,它会将其内容居中。

关于ios - 在 SwiftUI 中让 VStack 填满屏幕宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com