SwiftUI中具有水平和垂直对齐的布局 [英] Layout in SwiftUI with horizontal and vertical alignment
问题描述
我正在尝试完成此布局
如果我尝试将HStack封装在VStack中,则会得到以下信息:
如果我尝试将VStack封装在HStack中,则会得到以下信息:
是否可以通过基线将文本与文本字段对齐并从最长标签到对齐的文本字段开始获取标准间距?
不是专家,但我设法通过(1)选择2- VStacks
-in-a-<$实现了所需的布局c $ c> HStack 替代,(2)fr修改外部标签,(3)通过分配其 maxHeight = .infinity
摆脱默认的垂直扩展约束,并(4)固定 HStack
struct ContentView:查看{
@State var text =
let labels = [ Username, Email, Password]
变量主体:一些视图{
HStack {
VStack(alignment:.leading) {
ForEach(labels,id:\.self){{
中的标签Text(label)
.frame(maxHeight:.infinity)
.padding(.bottom,4 )
}
}
VStack {
ForEach(labels,id:\.self){Label in
TextField(label,text:self 。$ text)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
.padding(.leading)
}
.padding(.horizontal)
.fixedSize(horizontal:false,vertical:true)
}
}
这是结果预览:
)我手动添加了填充
信用到此网站,以启发我理解
SwiftUI布局技巧的路径
I'm trying to accomplish this layout
If I try HStack wrapped in VStack, I get this:
If I try VStack wrapped in HStack, I get this:
Is there a way to baseline align the text with the textfield and get standard spacing from the longest label to the start of the aligned textfields?
not an expert here, but I managed to achieve the desired layout by (1) opting for the 2-VStacks
-in-a-HStack
alternative, (2) framing the external labels, (3) freeing them from their default vertical expansion constraint by assigning their maxHeight = .infinity
and (4) fixing the height of the HStack
struct ContentView: View {
@State var text = ""
let labels = ["Username", "Email", "Password"]
var body: some View {
HStack {
VStack(alignment: .leading) {
ForEach(labels, id: \.self) { label in
Text(label)
.frame(maxHeight: .infinity)
.padding(.bottom, 4)
}
}
VStack {
ForEach(labels, id: \.self) { label in
TextField(label, text: self.$text)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
.padding(.leading)
}
.padding(.horizontal)
.fixedSize(horizontal: false, vertical: true)
}
}
Here is the resulting preview:
in order to account for the misaligned baselines of the external and internal labels (a collateral issue that is not related to this specific layout – see for instance this discussion) I manually added the padding
credits to this website for enlightening me on the path to understanding SwiftUI layout trickeries
这篇关于SwiftUI中具有水平和垂直对齐的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!