首页 > 解决方案 > SwiftUI 一个文本中心和一个尾随对齐

问题描述

我正在尝试向我制作的自定义图表视图添加一些细节。我目前在 VStack 中有图表和标题。这是完美的工作,意味着标题在图表上方居中。

我现在想在标题下方和视图尾端的图表上方添加一个小文本标题,如下所示

我想要的是

我正在努力理解我需要使用哪些修饰符来正确设置对齐以实现此布局。任何帮助表示赞赏。

代码:

VStack {
    // Title Text
    Text(title)
        .font(.headline)
    
    // The new text I want added (text 2 in the image)  
    Text(min)
        .font(.caption)
        // My current attempt but I am not sure this is right
        .alignmentGuide(.trailing, computeValue: { _ in 0 })
        
    // Chart
    ChartView()
}

标签: iosswiftswiftui

解决方案


只需将您的第二个包装Text在带有垫片的 HStack 中。该垫片将迫使Text向右。

struct ContentView: View {
    var body: some View {
        VStack {
            // Title Text
            Text("Title")
                .font(.headline)
            
            HStack {
                Spacer() /// forces the Text to the right
                
                // The new text I want added (text 2 in the image)
                Text("Text 2")
                    .font(.caption)
            }
            
            // Chart
            Rectangle()
                .fill(Color.blue)
        }
    }
}

结果:


推荐阅读