0

So I'm trying to draw a bar chart using the code below:

HStack(alignment: .bottom) {
                ForEach(0..<values.count) { idx in
                    let max = values.max() ?? 0
                    
                    VStack {
                        Text(labels[idx])
                            .font(.caption)
                            .rotationEffect(.degrees(-60))
                        
                        RoundedRectangle(cornerRadius: 5)
                            .fill(Color.white)
                            .frame(width: 20, height: CGFloat(values[idx]) / CGFloat(max) * geo.size.height * 0.6)
                        
                        Text(xAxisLabels[idx])
                            .font(.caption)
                    }
                }
            }.frame(maxWidth: .infinity, maxHeight: .infinity)
            .cornerRadius(10)
            .padding(.bottom, 20)
        }

Note line:

.frame(width: 20, height: CGFloat(values[idx]) / CGFloat(max) * geo.size.height * 0.6)

I am dynamically assigning the height to the bar chart from the values from HealthKit (The 'values' variable).

I'm just wondering is there anyway I could fix this issue? I have prior versions where the bar chart can be displayed using static variables and from what I can understand from the error it doesn't like the fact that the potential height is not static.

Dezkiir
  • 19
  • 4

1 Answers1

0

Try replacing 0 for 1 here:

let max = values.max() ?? 1

This will prevent a division by 0 when view is refreshing.

ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • Doesn't seem to make a difference, still seems to be the same issue. I am now wondering if it's s because I have the HealthData Interval set to daily, therefore the height is null as it has nothing to base it off. – Dezkiir Mar 29 '22 at 14:14
  • height 0 shouldn't be an issue. if only warns for negative and infinite (which usually results from division by 0). Anything that could become negative? – ChrisR Mar 29 '22 at 14:31
  • Another issue could be `ForEach(0.. – ChrisR Mar 29 '22 at 14:33
  • I have discovered the issue, it's in regards to reading from the HealthKit. For some reason it can only read certain types and not all. So now I have a new issue – Dezkiir Mar 29 '22 at 15:40