Bar Chart won't work with negative y values in Swift

Viewed 169

I am trying to create a bar chart that works with negative y values. Currently, when I input negative values, it does not work properly, I can't figure it out.

Right now, I'm thinking that when a negative value is there, I'll change the alignment of the bar so that it starts from that value (so like, if percent is -50, the bar will be aligned to -50 so that the tip touches the x axis), but I'm not sure how to do this.

Here is the code:

import SwiftUI

struct ContentView: View {
      var body: some View {
          
       HStack(alignment: .bottom, spacing: 8){
              
              ForEach(percents){i in
                  
                  Bar(percent: i.percent,day: i.day)
              }
              
          }.frame(height: 250)
      }
  }
  
  struct ContentView_Previews: PreviewProvider {
      static var previews: some View {
          ContentView()
      }
  }
  
  struct Bar : View {
      
      var percent : CGFloat = 0
      var day = ""
      
      var body : some View{
          
          VStack{
              
              Text(String(format: "%.0f", Double(percent)) + "%").foregroundColor(Color.black.opacity(0.5))
              
              Rectangle().fill(Color.red).frame(width: UIScreen.main.bounds.width / 7 - 12, height: getHeight())
              
              Text(day).foregroundColor(Color.black.opacity(0.5))
          }
          
      }
      
      func getHeight()->CGFloat{
          
          return 200 / 100 * percent
      }
  }
  
  
  // Sample Datas....
  
  struct type : Identifiable {
      
      var id : Int
      var percent :CGFloat
      var day : String
  }
  
  
  var percents = [
  type(id: 0, percent: -20, day: "Mon"),
  type(id: 1, percent: 50, day: "Tue"),
  type(id: 2, percent: -80, day: "Wed"),
  type(id: 3, percent: 60, day: "Thu"),
  type(id: 4, percent: 90, day: "Fri"),
  type(id: 5, percent: 100, day: "Sat"),
  type(id: 6, percent: -100, day: "Sun")
0 Answers
Related