所以我的问题是我试图对齐来自不同 HStack 的文本。不同大小的 SFSymbol 导致了这个问题。
我知道 AlignmentGuide 可以解决我的问题,但我不确定如何实施。如果有人能提供任何见解,我将不胜感激!
我已经看过WWDC talk。
不过我需要稍微澄清一下才能把它放在一起。
这是相关代码
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("SOS Mayday!").bold()
.font(.largeTitle)
Rectangle()
.frame(height: 1)
HStack {
Image(systemName: "textformat.abc").imageScale(.large)
Text("Trying to figure out how to use alignment guide").bold()
}.padding(.vertical)
HStack {
//MARK:- FIX ALIGNMENT
Image(systemName: "aqi.low").imageScale(.large)
Text("This text should align with the text above").bold()
}
Spacer()
}.padding(.horizontal)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
答案 0 :(得分:1)
我能够使用这些步骤生成您想要的输出:
这是更新的代码:
extension HorizontalAlignment {
private enum LeadingAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[.leading]
}
}
static let leadingAlign = HorizontalAlignment(LeadingAlignment.self)
}
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("SOS Mayday!").bold()
.font(.largeTitle)
Rectangle()
.frame(height: 1)
// The new VStack using the custom alignment.
VStack(alignment: .leadingAlign) {
HStack {
Image(systemName: "textformat.abc").imageScale(.large)
Text("Trying to figure out how to use alignment guide")
.bold()
.alignmentGuide(.leadingAlign) { d in
d[.leading]
}
}.padding(.vertical)
HStack {
//MARK:- FIX ALIGNMENT
Image(systemName: "aqi.low").imageScale(.large)
Text("This text should align with the text above")
.bold()
.alignmentGuide(.leadingAlign) { d in
d[.leading]
}
}
Spacer()
}
}.padding(.horizontal)
}
}