SwiftUI:对齐不同 HStack 中的视图? [英] SwiftUI: align views in different HStacks?
问题描述
对于列表视图中使用的每个单元格,我都有以下视图......:
I have the following view for each of the cells used in the List view....:
var body: some View {
VStack {
HStack {
Text("item: \(item.name)")
Text("Some text")
Spacer()
}
HStack {
Image(systemName: "squareshape.fill")
.resizable()
.frame(width: 30, height: 30)
Spacer()
}
}
}
看起来像这样:
我想将黑色方块与前一个 HStack 中的 Some text
前沿对齐.为了清晰起见,我对图像进行了注释,以直观地显示黑色方块应该落在的位置.
I want to align the black square to the Some text
leading edge found in the previous HStack. I annotated the image to visually show where the black square should land for clarity.
我已经查看了几个可能有解决方案的类似问题,但我还没有能够将我所看到的应用到我的需求中.我相信我需要使用对齐指南,但是,我不确定如何实际应用此类更改.
I have looked at a couple of similar questions that might have the solution in it but I haven't been able to apply what I saw to my need here yet. I believe I need to use alignment guides, but, I am not sure how to actually apply such change.
我想我可以在我可以使用 VStacks 等的地方以不同的方式打破布局......但是,我想知道在这种情况下如何让一个视图在 HStacks 中与另一个视图对齐......
I think I could break the layout out differently where I could be using VStacks etc... but, I want to know how to tell a view to align itself to another in this case across HStacks...
我怎样才能完成概述的内容?
How could I accomplish what outlined?
推荐答案
这是一个可能的方法的演示 - 基于自定义对齐指南,即.将相同的自定义对齐指南应用于不同的视图,使它们与该指南对齐/由该指南对齐.(实际上,对于这种情况,您不需要第二个 HStack
).
Here is a demo of possible approach - based on custom alignment guides, ie. applying same custom alignment guide to different views makes them aligned to/by that guide. (Actually you don't need second HStack
for this scenario).
使用 Xcode 12.5/iOS 14.5 测试
Tested with Xcode 12.5 / iOS 14.5
struct ContentView: View {
var body: some View {
List(0..<10) {
RowView(item: $0)
}
}
}
extension HorizontalAlignment {
private enum MyLeadingAlignment: AlignmentID {
static func defaultValue(in dimensions: ViewDimensions) -> CGFloat {
return dimensions[HorizontalAlignment.leading]
}
}
static let myLeading = HorizontalAlignment(MyLeadingAlignment.self)
}
struct RowView: View {
let item: Int
var body: some View {
VStack(alignment: .myLeading) {
HStack {
Text("item: \(item)")
Text("Some text")
.alignmentGuide(.myLeading) { $0[.leading] } // << here !!
Spacer()
}
Image(systemName: "squareshape.fill")
.resizable()
.frame(width: 30, height: 30)
.alignmentGuide(.myLeading) { $0[.leading] } // << here !!
}
}
}
这篇关于SwiftUI:对齐不同 HStack 中的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!