如何使用Swift在饼图中正确设置xValuePosition和yValuePosition?

时间:2017-10-21 21:20:22

标签: ios swift charts pie-chart ios-charts

我正在尝试将标签放在正确的位置,并将线条指向它们,但线条重叠,并且两侧的标签不会完全显示。如果线的长度增加,标签将被完全切割。

这就是我现在所得到的。 enter image description here

我想要的是什么 enter image description here

代码:

 `class ViewController: UIViewController{

    let pieView : PieChartView = {
    let set = PieChartView()
    set.translatesAutoresizingMaskIntoConstraints = false
    set.drawHoleEnabled = false
    set.chartDescription?.text = ""  
    return set  
    }()

    override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    navigationItem.title = "Pie"
    setChart()
    chartData()


}

   let surveyData = ["cat": 20, "dog": 30, "both": 5, "neither": 45]

func setChart(){
    view.addSubview(pieView)
    pieView.centerXAnchor.constraint(equalTo:    view.centerXAnchor).isActive = true
    pieView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    pieView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true
    pieView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5).isActive = true

}

func chartData(){
    var data = [PieChartDataEntry]()
    for (key,value) in surveyData{

        let entry = PieChartDataEntry(value: Double(value), label: key)
        data.append(entry)
    }
    let chart = PieChartDataSet(values: data, label: "")
    chart.colors = ChartColorTemplates.material()
    chart.sliceSpace = 2
    chart.selectionShift = 5
    chart.xValuePosition = .outsideSlice
    chart.yValuePosition = .outsideSlice
    chart.valueTextColor = .black
    chart.valueLineWidth = 0.5
    chart.valueLinePart1Length = 0.2
    chart.valueLinePart2Length = 4
    chart.drawValuesEnabled = true
    let chartData = PieChartData(dataSet: chart)
    pieView.data = chartData
 }}`

1 个答案:

答案 0 :(得分:0)

请尝试使用您的数据集:

chart.selectionShift = 0