使用自定义 AlignmentGuide 的正确方法

时间:2021-04-06 15:18:28

标签: swiftui

所以我的问题是我试图对齐来自不同 HStack 的文本。不同大小的 SFSymbol 导致了这个问题。

我知道 AlignmentGuide 可以解决我的问题,但我不确定如何实施。如果有人能提供任何见解,我将不胜感激!

Text poorly aligned

我已经看过WWDC talk

这是与此问题相关的主屏幕,screenshot of WWDC talk

WWDC screenshot

不过我需要稍微澄清一下才能把它放在一起。

这是相关代码

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()
    }
}

1 个答案:

答案 0 :(得分:1)

我能够使用这些步骤生成您想要的输出:

  1. 根据 AlignmentID 和 a 创建自定义对齐枚举 它的静态实例,如您链接的幻灯片所示。
  2. 仅在要自定义对齐的部分周围添加新的 VStack。否则会影响其他组件的对齐。
  3. 在要对齐的两个文本上添加一个alignmentGuide() 领先优势。

这是更新的代码:

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)
    }
}