我正在尝试 Swifts Charts。我正在尝试将注释与图表顶部对齐,但我无法做到这一点。
但是这是通过图表顶部的
HStack
完成的,并且它没有 100% 对齐。所以我改用注释修饰符。结果是这样的:
但是正如您所看到的,这些值直接位于栏的顶部,这不是我正在寻找的结果。
用于注释的代码在这里:
.annotation {
Text("\(Int(item.price))")
.font(.system(size: 8))
.rotationEffect(.degrees(270))
.padding()
}
我尝试添加一个
VStack
,在下面放入Text
和一个Spacer
,但这没有帮助。我也尝试过:
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
但这也没有帮助。
希望你们能在这里帮助我:) 提前致谢。
您可以使用
.annotation(position: .overlay, alignment: .bottom)
,它可以为您提供从标记底部开始的标记上的注释叠加。
这是一个例子:
struct ContentView: View {
let data: [(Int, Int)] = {
(0...20).map { ($0, Int.random(in: 0...500)) }
}()
@State private var selectedX = 6
var body: some View {
VStack {
Chart {
ForEach(data.indices, id: \.self) { i in
let (x,y) = data[i]
BarMark(
x: .value("x", x),
y: .value("y", y)
)
.annotation(position: .overlay, alignment: .bottom, spacing: 0) {
Text("\(y)")
.font(.system(size: 8))
.frame(width: 570 , alignment: .trailing)
.rotationEffect(.degrees(-90))
}
}
}
.chartXScale(domain: 0...20)
.chartYScale(domain: 0...550)
.chartYAxis(.hidden)
.frame(height: 300)
}
.padding()
}
}