我观看了WWDC的Building Custom Views with SwiftUI视频,其中介绍了使用SwiftUI的一些高级技术,但是我无法对齐不在同一HStack中的底部元素,请参见下图:
基本上,我想将个人资料图像与“文本”视图的底部对齐,但它不起作用,我使用.alignmentGuide
修饰符从视频中跟踪了相同的代码,但它不起作用。谢谢!
struct MessageView : View {
var body: some View {
HStack {
HStack(alignment: .center) {
RoundImage(image: Image("turtlerock"))
.frame(width: 35)
.alignmentGuide(.bottomImageAndText) { d in
d[.bottom]
}
VStack(alignment: .leading) {
Text("AR demo from Apple site ? AR demo from Apple site ? AR demo from Apple site ? AR demo from Apple site ?")
.fontWeight(.regular)
.padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
.lineLimit(5)
.border(Color.gray, width: 1, cornerRadius: 15)
.layoutPriority(2)
.alignmentGuide(.bottomImageAndText) { d in
d[.bottom]
}
HStack {
Image(systemName: "heart.fill")
.foregroundColor(.red)
RoundImage(image: Image("turtlerock"))
.frame(height: 16)
}
.padding(.leading)
}
}.padding(EdgeInsets(top: 0, leading: 10, bottom:0 , trailing: 0))
.layoutPriority(1)
Spacer()} }
}
extension VerticalAlignment {
private enum BottomImageAndText : AlignmentID {
static func defaultValue(in d: ViewDimensions) -> Length {
return d[.bottom]
}
}
static let bottomImageAndText = VerticalAlignment(BottomImageAndText.self)
}
答案 0 :(得分:0)
为了使对齐指南正常工作,您需要将其附加到堆栈上。例如:
HStack {
HStack (alignment: .bottomImageAndText) {
答案 1 :(得分:0)
注意:除非自定义对齐方式与“容器对齐”参数值匹配,否则在布局过程中将忽略自定义alignment guide
。
我对您的代码进行的更改:
struct MessageView : View {
var body: some View {
HStack {
HStack(alignment: .bottomImageAndText) {
Image("turtlerock")
.frame(width: 35, height: 35, alignment: .bottom)
.alignmentGuide(.bottomImageAndText) { d in
d[.bottom]
}
....
有关alignment guide
的更多信息,您可以浏览this article。