自定义tableviewcell中的PieChartView

时间:2018-07-22 02:56:40

标签: swift uitableview charts

我有一个带有一个单元格(自定义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")
}
}

所以问题是如何/何时正确设置自定义单元格的“属性”和“值”变量?

1 个答案:

答案 0 :(得分:1)

您创建PieChartView,并通过init函数将其添加到屏幕上。然后在cellForRow上更新其属性,而不重新呈现PieChartView

  1. 最简单的解决方案是在createPieChart()中设置属性后调用cellForRow(别忘了清除单元格并准备好进行重用)。

  2. 我希望在createPieChart()上调用awakeFromNib()并实现另一个函数来设置属性并在PieChartView上重新渲染cellForRow

相关问题