SwiftUI图表 - Y轴标题翻转

4
考虑以下的 SwiftUI Charts 视图:
struct ChartView: View {
    var data: [DataPoint]
    
    var body: some View {
        Chart {
            ForEach(data) { point in
                LineMark (
                   x: .value("x", point.x),
                   y: .value("y", point.y)
                )
            }
            .interpolationMethod(.cardinal)
        }
        .chartYAxis {
            AxisMarks(position: .leading)
        }
        .chartXAxisLabel(position: .bottom, alignment: .center) {
            Text("x title")
        }
        .chartYAxisLabel(position: .leading, alignment: .center) {
            Text("y title")
        }
        .padding(10)
    }
}

这是结果:

enter image description here

请注意 Y 轴标题已经翻转。我该如何将 Y 轴标题翻转 180 度?
1个回答

1

旋转 Y 轴标题

尝试使用 rotationEffect(_:anchor:) 实例方法的以下解决方法(您必须将 Y 标签 绕 Z 轴旋转 +270 或 -90 度),预先重新定义文本框架:

struct ChartView: View {
    
    var data: [DataPoint]
    
    var body: some View {
        Chart {
            ForEach(data) { point in
                LineMark(x: .value("x", point.x),
                         y: .value("y", point.y)
                )
            }
            .foregroundStyle(.pink)
            .interpolationMethod(.cardinal)
            .lineStyle(.init(lineWidth: 5.0))
            .shadow(color: .gray, radius: 15)
        }
        .chartXAxisLabel(position: .bottom, alignment: .center) {
            Text("X values")
                .font(.title3)
                .foregroundColor(.black)
        }
        .chartYAxisLabel(position: .topLeading) {
            Text("Y values")
                .font(.title3)
                .foregroundColor(.black)
                .frame(maxWidth: 100, maxHeight: 70)                 // 1
                .rotationEffect(.degrees(270), anchor: .center)      // 2
                .offset(y: UIScreen.main.bounds.midY)                // 3
        }
        .padding(.init(top: 10, leading: 40, bottom: 30, trailing: 20))
    }
}

enter image description here

import SwiftUI
import Charts

struct DataPoint: Identifiable {
    let id = UUID()
    let x: Int
    let y: Int
}

struct ContentView: View {      
    let data: [DataPoint] = [
        .init(x: 10, y: 50), .init(x: 20, y: 5),  .init(x: 30, y: -10),
        .init(x: 40, y: 80), .init(x: 50, y: 15), .init(x: 60, y: 21),
        .init(x: 70, y: -5), .init(x: 80, y: 37), .init(x: 90, y: -50)
    ]        
    var body: some View {
        ZStack {
            Color.gray.opacity(0.3).ignoresSafeArea()
            ChartView(data: data).ignoresSafeArea()
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接