Home > Enterprise >  How to make each individual bar in a bar chart have the same starting point
How to make each individual bar in a bar chart have the same starting point

Time:11-09

I'm creating a very simple bar chart by using SwiftUI's enter image description here

How do I modify my code so that the bar marked as 14-09-2021 can be on the same line as the rest?

Here's the code I use to create these individual bar charts:

        VStack {
        Spacer()
        Text(history.target)
        Rectangle()
            .fill(trackingViewModel.starColor(stars: history.target))
            .frame(width: 70, height: trackingViewModel.barHeight(stars: history.target))
        Text(history.date)
        Spacer()
    }

And then I use ForEach to create the barchart:

        HStack {
        ForEach(trackingViewModel.trackingHistory, id: \.self) { history in
            HStack(spacing: 5) {
                IndividualHistoryBar(history: history, trackingViewModel: trackingViewModel)
            }
                
        }

EDIT:

I forgot to mention that I call this history chart view by using a sheet. I tried Asperi's solution by adding .alignment to the HStack, but that didn't do anything. Could this be the reason? Does the sheet automatically align everything to the center?

CodePudding user response:

You need to set alignment

HStack(alignment: .bottom) {    // << here !!
   ForEach(trackingViewModel.trackingHistory, id: \.self) { history in

CodePudding user response:

I fixed it! The trick was to use alignment .lastTextBaseline, which takes the date as the baseline and aligns everything accordingly.

End result:

enter image description here

Modified code:

    HStack(alignment: .lastTextBaseline) { // <-- here!
        ForEach(trackingViewModel.trackingHistory, id: \.self) { history in
            HStack(spacing: 5) {
                IndividualHistoryBar(history: history, trackingViewModel: trackingViewModel)
            }                   
        }
    }
  • Related