首页 > 解决方案 > 想要移动数值数字坐在柱状图的顶部

问题描述

// 这将创建一个条形图,按 dateCreated 显示 item.totalscore。// 我怎样才能把 item.totalscore 放在栏的末尾?

var body: some View {
    VStack{
        Text("Prior scores")
        ForEach(items, id: \.self) { item in
          HStack{
            Text(Date2String(someDate: item.dateCreated!)).font(.caption2)
            Rectangle()
            .fill(BarChartColors(answer: item.totalscore))
            .scaleEffect(CGSize(width: (Double(item.totalscore)+0.5)), height: 0.7), anchor: .leading)
            Text("\(item.totalscore)").font(.caption2)
          }
        }
      }.padding()
    Spacer()
  }

标签: swiftuibar-chart

解决方案


尝试这样的事情:(注意你需要锻炼规模)

@State var max = 250.0  // <-- to be determined
let maxw = 333.0 // <-- to be determined
let h = 22.0 // <-- to be determined

 var body: some View {
     VStack{
         Text("Prior scores")
         ForEach(items, id: \.self) { item in
           HStack{
             Text(Date2String(someDate: item.dateCreated!)).font(.caption2)
             Rectangle()
             .fill(BarChartColors(answer: item.totalscore))
             .scaleEffect(CGSize(width: Double(item.totalscore)+0.5, height: 0.7), anchor: .leading)
             .frame(width: item.totalscore / max * maxw, height: h)
             .clipped()  // <--- here

             Text("\(item.totalscore)").font(.caption2)
             Spacer()  // <--- here
           }
         }
       }.padding()
        .onAppear {
            max = items.map { Double($0.totalscore) }.max() ?? 0.0
        }
     Spacer()
   }

推荐阅读