Charts库3.1.1版本是否支持无数据时显示提示消息?
解决Charts 3.1.1版本无数据时显示提示消息的问题
我之前在使用Charts 3.x版本时也碰到过一模一样的困扰——旧版本里的noDataTextDescription属性确实被移除了,而默认的chartDescription只能固定在右下角显示,完全满足不了无数据时居中提示的需求。这里分享两个我亲测有效的解决方案:
方案一:继承ChartView重绘无数据文本
这种方式能让你完全自定义提示文本的样式、位置,灵活性拉满。以LineChartView为例,你可以创建一个自定义子类:
class CustomLineChartView: LineChartView { override func draw(_ rect: CGRect) { super.draw(rect) // 检查图表是否无数据 guard let chartData = data, chartData.entryCount == 0 else { return } // 配置无数据提示文本的样式 let noDataText = "暂无数据,请稍后重试" let textAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 18, weight: .medium), .foregroundColor: UIColor.darkGray ] // 计算文本位置,确保居中显示 let textSize = noDataText.size(withAttributes: textAttributes) let centerX = bounds.midX - textSize.width / 2 let centerY = bounds.midY - textSize.height / 2 // 绘制提示文本 noDataText.draw(at: CGPoint(x: centerX, y: centerY), withAttributes: textAttributes) } }
之后直接用CustomLineChartView替代原生的LineChartView即可,当图表没有数据时,会自动居中显示你设置的提示文本。
方案二:添加子视图作为无数据提示
如果不想继承重绘,这种方法更简单直接——给ChartView加一个默认隐藏的提示标签,根据数据状态控制显示/隐藏:
// 初始化图表并添加到视图 let chartView = LineChartView(frame: view.bounds) view.addSubview(chartView) // 创建无数据提示标签 let noDataLabel = UILabel() noDataLabel.text = "暂无数据" noDataLabel.textColor = .gray noDataLabel.font = UIFont.systemFont(ofSize: 16) noDataLabel.sizeToFit() noDataLabel.center = chartView.center noDataLabel.isHidden = true // 默认隐藏 chartView.addSubview(noDataLabel) // 更新图表数据时切换标签状态 func updateChartData(with newData: LineChartData?) { chartView.data = newData noDataLabel.isHidden = newData?.entryCount ?? 0 > 0 }
这种方法的优势是实现快,不需要改动ChartView的原有逻辑,适合快速迭代的场景。
两种方案都能完美解决无数据提示的问题,你可以根据自己的需求选——需要高度自定义就用方案一,追求快速实现就选方案二。
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

