【问题标题】:To display multiple charts like Bar chart,Pie chart, line chart in a single collection view in a view controller在视图控制器的单个集合视图中显示多个图表,如条形图、饼图、折线图
【发布时间】:2017-11-22 07:37:24
【问题描述】:

我的应用程序的要求是,我需要在视图控制器的集合视图中显示不同的图表,例如饼图、折线图、条形图等。 我打算使用最常用的库来创建图表https://github.com/danielgindi/Charts。要在页面上单独实现每种类型的图表,我们必须创建图表类的 UIView。例如,要实现饼图,我们必须创建类 PieChartView 的视图。 我的问题是,如果我们想要在一个集合视图中使用不同的图表,我们该如何实现呢?由于我是 swift 开发代码示例的新手,因此真的很有帮助。

提前致谢。

【问题讨论】:

    标签: ios swift swift3 charts collectionview


    【解决方案1】:

    假设显示集合视图的视图控制器名为 StatsVC,那么您需要在界面生成器中向其添加集合视图,单击 collectionViewCell 并为其提供重用标识符(例如 chartCell),然后在代码中: class StatcVC:UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { //create your charts here and put them in an array to be easier later on func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int -> Int { return numberOfCellsYouNeed } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath) -> UICollectionVIewCell{ if let cell = collectionView.dequeueReusableCell(withIdentifier:"chartCell", for: indexPath) { cell.addSubView(chartViews[indexPath.row]) return cell }else{ return UICollectionViewCell() }}

    这是实现它的基本方法,但它可能看起来不太漂亮,下一步是创建一个自定义 collectionViewCell 类并在 InterfaceBuilder 中设计它,然后在 ChartCell 自定义类 (UICollectionVIewCell) 中连接插座和在 StatsVC 中使用此自定义单元格。自定义单元格的优点是您可以在顶部/底部有一个标签,用于描述图表或您需要的任何其他 UI 元素。如果您将所有图表视图保存在一个数组中,您可以使用上述方法非常轻松地将它们添加到 collectionView 中。

    更新 要以编程方式创建视图,您可以这样做:

    let barChartView1 = BarChartView() let barChartView2 = BarChartView() barChartView1.data = ...// you do what you need to do here, I'm not familiar with your data/code... var chartViews = [barChartView1, barChartView2] 最后,正如您在上面看到的,您可以使用 indexPath.row 作为数组索引来拉出下一个 chartView 并将其放入 collectionViewCell 中。使用集合和表格视图并不是一件容易的事,所以我建议在 Apple 图书馆度过一个美好的夜晚。 Tjios 文章详细解释了它。 https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/CollectionViewBasics/CollectionViewBasics.html

    【讨论】:

    • 感谢您的帮助。但是 github.com/danielgindi/Charts 。描述了只在界面生成器中添加视图的类。我不知道如何以编程方式添加它并将其添加到数组中。你能分享我的代码示例吗。提前致谢。
    • @user8986838 你有什么解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多