Harry Day
Harry Day

Reputation: 408

SwiftUI Align one text centre and one trailing

I am trying to add some detail to a custom chart view that I have made. I currently have the chart and the title in a VStack. This is working perfectly and means the title is centred above the chart.

I now want to add a small text caption just underneath the title and above the chart on the trailing side of the view as shown below

What I want

I am struggling to understand what modifiers I need to use to set the alignment correctly to achieve this layout. Any help is appreciated.

Code:

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

Upvotes: 1

Views: 842

Answers (1)

aheze
aheze

Reputation: 30228

Just wrap your second Text in an HStack with a spacer. This spacer will force the Text to the right.

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

Result:

Upvotes: 1

Related Questions