我已使用以下库在当前项目中显示饼图:https://github.com/danielgindi/Charts。
但是,我在iPhone较小型设备中遇到饼图问题。我已经实现了以下代码来显示pi图表:
class ChartVC: UIViewController {
@IBOutlet weak var pieChartView : PieChartView!
var arrPiChartData : [PiChartData]?
func setupPiChart() {
let l = pieChartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .bottom
l.orientation = .vertical
l.xEntrySpace = 0
l.yEntrySpace = 0
l.yOffset = 0
l.font = self.isPhone ? Typography.robotoRegular14 : Typography.robotoRegular18
self.pieChartView.entryLabelFont = Typography.robotoRegular14
self.pieChartView.drawHoleEnabled = false
self.pieChartView.notifyDataSetChanged()
}
func setupData() {
var arr = [PieChartDataEntry]()
if self.arrPiChartData != nil {
for piChartData in self.arrPiChartData! {
var name = ""
if let strName = piChartData.name {
name = strName
}
var value = 0.0
if let floatValue = piChartData.percentAmount {
value = Double(floatValue)
}
let entry = PieChartDataEntry(value: value, label: name)
arr.append(entry)
}
let set = PieChartDataSet(values: arr, label: "Total Sales by Company Users")
set.drawIconsEnabled = false
set.sliceSpace = 2
set.xValuePosition = .outsideSlice
set.entryLabelColor = UIColor.black
set.entryLabelFont = self.isPhone ? Typography.robotoRegular14 : Typography.robotoRegular18
set.colors = self.arrColours
let data = PieChartData(dataSets: [set])
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .percent
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
pFormatter.percentSymbol = " %"
data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter))
self.pieChartView.data = data
} else {
self.pieChartView.data = nil
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupPiChart()
self.setupData()
}
//------------------------------------------------------------------------------
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.pieChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)
}
}
此代码可显示饼图。但是,当我在iPhone SE,5S,6、7、8等小型设备上运行应用程序时出现问题。标签数据与饼图重叠。
请参见下面的图片,该图片将描述实际的问题。
我试图找到解决方案,但没有得到。
我需要帮助来解决此问题或更好的解决方案。
答案 0 :(得分:1)
由于没有很好的方法在饼图中垂直显示更多图例,因此我更新了代码以在水平方向显示它。另外,标题在饼图中无法正确显示,因此请将其删除。为此,我将代码更新如下,以显示正确的饼图:
func setupPiChart() {
// This will align label text to top right corner
let l = pieChartView.legend
l.horizontalAlignment = .left
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.xEntrySpace = 10
l.yEntrySpace = 0
l.font = self.isPhone ? Typography.robotoRegular14 : Typography.robotoRegular18
self.pieChartView.entryLabelFont = Typography.robotoRegular14
self.pieChartView.drawHoleEnabled = false
self.pieChartView.drawEntryLabelsEnabled = false
self.pieChartView.notifyDataSetChanged()
}
现在,如以下图片所示,它的显示效果很好: