【发布时间】:2020-11-21 23:44:29
【问题描述】:
我正在尝试在两个不同的 HStack 中对齐文本,但很难让第二个(较短的长度)与第一个 HStack 对齐。我尝试过使用 .frame(minWidth:0, maxWidth: .infinity) 和 Spacer(),但找不到解决方案。这可能吗?
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
HStack {
Spacer()
Text("Lorem ipsum dolor")
.font(.system(size: 22, weight: .ultraLight, design: .rounded))
Spacer()
}.padding()
.overlay(
Rectangle()
.stroke(Color(#colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)), style: StrokeStyle(lineWidth: 0.5, dash: [5.0])))
HStack {
Spacer()
Text("Lorem ipsum")
.font(.system(size: 22, weight: .ultraLight, design: .rounded))
Spacer()
}.padding()
.overlay(
Rectangle()
.stroke(Color(#colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)), style: StrokeStyle(lineWidth: 0.5, dash: [5.0])))
}
}
}
我尝试使用 HorizontalAlignment 指南,但它们偏离了中心:
struct ContentView: View {
var body: some View {
VStack(alignment: .controlLeadingEdge) {
HStack {
Text("Lorem ipsum dolor")
.font(.system(size: 22, weight: .ultraLight, design: .rounded))
.alignmentGuide(.controlLeadingEdge, computeValue: { d in d[HorizontalAlignment.leading] })
}.padding()
.frame(minWidth: 0, maxWidth: 300)
.overlay(
Rectangle()
.stroke(Color(#colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)), style: StrokeStyle(lineWidth: 0.5, dash: [5.0])))
HStack {
Text("Lorem ipsum")
.font(.system(size: 22, weight: .ultraLight, design: .rounded))
.alignmentGuide(.controlLeadingEdge, computeValue: { d in d[HorizontalAlignment.leading] })
}.padding()
.frame(minWidth: 0, maxWidth: 300)
.overlay(
Rectangle()
.stroke(Color(#colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)), style: StrokeStyle(lineWidth: 0.5, dash: [5.0])))
}
}
}
extension HorizontalAlignment {
private enum ControlAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[HorizontalAlignment.controlLeadingEdge]
}
}
static let controlLeadingEdge = HorizontalAlignment(ControlAlignment.self)
}
【问题讨论】:
-
您希望它如何对齐?你想让最长的一个居中,另一个与最长的前缘对齐吗?第二个总是更短吗?
-
@vacawama 我想让最短的与最长的前缘对齐。是的,这是正确的,第二个也会更短。谢谢
标签: swiftui