iOS图表如何调整饼图高度

时间:2018-10-28 20:49:46

标签: charts swift4 ios-charts

我试图将饼图正确地拟合到比图表高得多的视图中。问题是我想在图表底部包括一个垂直的图例列表,这使实际图表的高度动态变化。如果我在数据集中的条目过多,则图表底部将再显示一个图例行。

是否有一种实用的方法来获取图表的“实际”或“渲染”高度,以便可以将pieChart.frame.height设置为此值?否则,如何调整图表的高度,使其包括图例在内的所有内容?

enter image description here

@IBOutlet weak var pieChart: PieChartView!

var aDataEntry = PieChartDataEntry(value:30)
var bDataEntry = PieChartDataEntry(value:25)

var dataEntries = [PieChartDataEntry]()



override func viewDidLoad() {
    super.viewDidLoad()

    pieChart.chartDescription?.text = "A test"
    aDataEntry.label = "A"
    bDataEntry.label = "B"

    dataEntries = [aDataEntry, bDataEntry]

    updateChartData()

    // Do any additional setup after loading the view.
}

func updateChartData() {
    let chartDataSet = PieChartDataSet(values: dataEntries, label:nil)
    let chartData = PieChartData(dataSet: chartDataSet)
    var colours:[UIColor] = []
    for i in 1..<10 {
        colours.append(UIColor(named: "Colour" + String(i))!)
    }
    chartDataSet.colors = colours 
    pieChart.data = chartData
    pieChart.usePercentValuesEnabled = true
    pieChart.legend.orientation = .vertical
    pieChart.notifyDataSetChanged()
    print(pieChart.frame.height)
}

1 个答案:

答案 0 :(得分:1)

添加/设置图例后,只需调用pieChartView.notifyDataSetChanged(),否则,图例将消失。 这是示例:

pieChartView.legend.verticalAlignment = .bottom
pieChartView.legend.horizontalAlignment = .center
pieChartView.legend.orientation    = .vertical
pieChartView.notifyDataSetChanged()

编辑1:要快速解决问题,请在调用 PieChartDataSet 时使用空字符串代替 nil

let chartDataSet = PieChartDataSet(values: dataEntries, label:"")