我有一个视图,其中包含一个包含两个视图的 HStack。右视图包含一个图表。左视图包含图形 Y 轴的标签。我想将图表放在其父视图的中心。如果有人能指出我正确的方向来实现这一点,我将不胜感激。下面是我的代码。
问候,
克里斯
import SwiftUI
struct MainView: View {
@EnvironmentObject var viewModel : ViewModel
var body: some View {
VStack (alignment: .center) {
let maxYValue = viewModel.data.max { $0.Value < $1.Value }?.Value
let minYValue = viewModel.data.max { $0.Value > $1.Value }?.Value
let deltaY = maxYValue! - minYValue!
let maxYVal = Int(round(maxYValue!))
let minYVal = Int(round(minYValue!))
HStack{
VStack{
Text(String("\(maxYVal)"))
Spacer()
Text("2")
Spacer()
Text("3")
Spacer()
Text("3")
Spacer()
Text(String("\(minYVal)"))
}.frame(width: 100, height: 510, alignment: .trailing)
GeometryReader { geometry in
Path { path in
for index in viewModel.data.indices {
let xPosition = ((geometry.size.width) / (CGFloat(viewModel.data.count - 1))) * CGFloat(index + 0)
let yPosition = (1 - (CGFloat(viewModel.data[index].Value - minYValue!)) / CGFloat(deltaY) ) * (geometry.size.height)
if index == 0 {
path.move(to: CGPoint(x : xPosition, y : yPosition))
}
path.addLine(to: CGPoint(x : xPosition, y: yPosition))
}
} .stroke(Color.blue, style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))
Path { path in
path.move(to: CGPoint(x: 0, y: geometry.size.height))
path.addLine(to: CGPoint(x: 0, y: 0))
path.move(to: CGPoint(x: 0, y: geometry.size.height))
path.addLine(to: CGPoint(x: geometry.size.width, y: geometry.size.height))
}.stroke(Color.black, style: StrokeStyle(lineWidth: 2))
Path { path in
for index in 0...3 {
path.move(to: CGPoint(x: 0 , y: geometry.size.height * CGFloat(index) / 4))
path.addLine(to: CGPoint(x: geometry.size.width , y: geometry.size.height * CGFloat(index) / 4))
}
}.stroke(Color.gray, style: StrokeStyle(lineWidth: 0.5))
} // end geometry reader
.frame(width: 700, height: 500)// end inner geometry reader
}
} // end of vstack
}
}