我有一个带有一个单元格(自定义 tableviewcell)的 tableview 部分。在这个自定义 tableviewcell 中,我试图放置一个饼图。 piechartview 出现了,但饼图本身(带有数据)没有出现。自定义单元格没有收到“属性”和“值”数据,即使我在创建自定义单元格时在 tableview 的 cellforrow 函数中设置了这些数据。顺便说一句,我正在以编程方式进行所有操作。
我像这样注册单元格:
statisticsTable.register(PieChartCell.self, forCellReuseIdentifier: "cellId2")
并在这里创建单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch headerTitles[indexPath.section]{
case "Diet":
let cell:PieChartCell = tableView.dequeueReusableCell(withIdentifier: "cellId2", for: indexPath) as! PieChartCell
cell.properties = ["United States","Mexico","Canada","Chile"]
cell.values = [1000.0,2000.0,3000.0,4000.0]
return cell
default:
return UITableViewCell()
}
}
无需注意下面类中的 createPieChart() 函数,因为我已经使用非自定义单元格 (UITableViewCell) 对其进行了测试并且饼图出现了(我只是无法让它显示在自定义单元格中).
class PieChartCell:UITableViewCell{
var properties = [String]()
var values = [Double]()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
var dietChart = PieChartView(frame: CGRect(x:0,y:0,width:400,height:400))
dietChart.backgroundColor = .clear
createPieChart(chart: dietChart,property: properties, value: values)
}
func createPieChart(chart:PieChartView,property:[String],value:[Double]) {
var entries = [PieChartDataEntry]()
for (index, value) in value.enumerated() {
let entry = PieChartDataEntry()
entry.y = value
entry.label = property[index]
entries.append( entry)
}
let set = PieChartDataSet( values: entries, label: nil)
colors = [UIColor.green,UIColor.cyan,UIColor(red:218/255 ,green:165/255 ,blue:32/255,alpha:1.0 ),UIColor.blue,UIColor.red]
set.colors = colors
let data = PieChartData(dataSet: set)
chart.data = data
chart.noDataText = "No data available"
chart.isUserInteractionEnabled = true
chart.backgroundColor = .clear
let d = Description()
d.text = ""
chart.chartDescription = d
chart.holeColor = UIColor(red:255,green:255,blue:255,alpha:0.5)
self.addSubView(chart)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
所以问题是如何/何时正确设置自定义单元格的“属性”和“值”变量?
最佳答案
您创建您的 PieChartView
并在 init
函数中将其添加到您的屏幕。然后在 cellForRow
上更新它的属性,而不是重新呈现您的 PieChartView
。
最简单的解决方案是在
cellForRow
中设置属性后调用createPieChart()
(不要忘记清除单元格并准备重新使用).我更愿意在
awakeFromNib()
上调用createPieChart()
并实现另一个函数来设置属性并重新呈现PieChartView
在cellForRow
上。
关于swift - 自定义 tableviewcell 中的 PieChartView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51461665/