You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Swift Charts坐标轴刻度的字体大小与颜色

修改Swift Charts坐标轴刻度标签的字体与颜色

方法1:直接自定义轴刻度标签样式

通过chartXAxis和chartYAxis修饰符,搭配AxisMarks可以精准控制刻度标签的字体大小与颜色:

Chart {
    // 替换成你的图表数据系列,例如LineMark、BarMark等
    LineMark(
        x: .value("日期", "2024-01"),
        y: .value("数值", 100)
    )
}
.chartXAxis {
    AxisMarks(position: .bottom) {
        AxisGridLine()
        AxisTick()
        AxisLabel(
            centered: true,
            style: AxisLabelStyle(
                font: .system(size: 16), // 设置刻度标签字体大小
                foregroundColor: .darkGray // 设置刻度标签颜色
            )
        )
    }
}
.chartYAxis {
    AxisMarks(position: .leading) {
        AxisGridLine()
        AxisTick()
        AxisLabel(
            style: AxisLabelStyle(
                font: .system(size: 14),
                foregroundColor: .blue
            )
        )
    }
}

方法2:创建可复用的自定义标签样式

如果需要在多个图表中统一刻度样式,可以定义自定义AxisLabelStyle:

struct CustomAxisLabelStyle: AxisLabelStyle {
    var fontSize: CGFloat = 15
    var textColor: Color = .black
    
    func body(content: AxisLabelContent) -> some View {
        content
            .font(.system(size: fontSize))
            .foregroundColor(textColor)
    }
}

// 使用示例
Chart {
    // 数据系列
}
.chartXAxis {
    AxisMarks {
        AxisLabel(style: CustomAxisLabelStyle(fontSize: 16, textColor: .darkGray))
    }
}

额外提示

  • 字体参数支持自定义字体,比如.custom("PingFangSC", size: 16)
  • 只需调整单个属性时,不用写全所有参数,比如只改颜色就只设置foregroundColor

内容的提问来源于stack exchange,提问作者profTC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:40:57