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

使用Charts pod的LineChartView如何设置Y轴固定最大值

解决方法

Charts 库的轴范围配置需要绑定到具体的轴实例,你当前仅启用了左侧Y轴,只需在初始化图表时关闭自动轴范围适配,手动固定最大值即可:

修改步骤

  • 在 viewDidLoad 方法的 chartView 配置段添加以下3行代码:
// 关闭Y轴自动跟随数据调整范围的逻辑
chartView.leftAxis.autoScaleMinMaxEnabled = false
// 固定Y轴最小值为0
chartView.leftAxis.axisMinimum = 0
// 固定Y轴最大值为10000
chartView.leftAxis.axisMaximum = 10000
  • 无需调整手势触发的didSwipe中的数据更新逻辑,轴范围固定后,每次a值更新时曲线会直接在固定Y轴范围内显示高度变化,不会再出现曲线视觉上无变化、仅Y轴刻度变动的问题。

修改后完整代码

import UIKit
import Charts

class ViewController: UIViewController {
    
    var a: Double = 1
   
    var line = LineChartDataSet()
    let chartView = LineChartView()
    let data = LineChartData()
    
    @objc private func didSwipe(_ sender: UIPanGestureRecognizer) {
        if sender.state == .changed{
            
            a = Double.random(in: 0.0...4.0)
            
            data.removeDataSet(line)
            line.removeAll()
            
            line.colors = [.black]
            line.drawCirclesEnabled = false
            line.label = nil
            
            for i in 0...100{
                let value = ChartDataEntry(x: Double(i), y: Double(i*i) * a)
                line.append(value)
            }
            data.addDataSet(line)
            chartView.data = data
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let swipe = UIPanGestureRecognizer()
        swipe.addTarget(self, action: #selector(didSwipe(_:)))
        
        line.colors = [.black]
        line.drawCirclesEnabled = false
        line.label = nil
        
        for i in 0...100{
            let value = ChartDataEntry(x: Double(i), y: Double(a) * Double(i*i))
            line.append(value)
        }
        
        data.addDataSet(line)
        
        chartView.data = data
        chartView.leftAxis.enabled = true
        chartView.rightAxis.enabled = false
        chartView.xAxis.enabled = false
        chartView.pinchZoomEnabled = false
        chartView.doubleTapToZoomEnabled = false
        // 新增Y轴固定配置
        chartView.leftAxis.autoScaleMinMaxEnabled = false
        chartView.leftAxis.axisMinimum = 0
        chartView.leftAxis.axisMaximum = 10000
        chartView.animate(xAxisDuration: 1)
        chartView.frame = view.safeAreaLayoutGuide.layoutFrame
        chartView.addGestureRecognizer(swipe)
        
        view.addSubview(chartView)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:45:04