LoginSignup
7
8

More than 5 years have passed since last update.

Charts:タップした際の処理

Posted at

チャートを描きたいときに便利なライブラリ Charts で、チャートをタップした際の処理を共有します。

import UIKit
import Charts

class ChartViewController: UIViewController, ChartViewDelegate {

    @IBOutlet weak var pieChartView: PieChartView!

    override func viewDidLoad() {
        super.viewDidLoad()

        pieChartView.delegate = self

        let summeryList = [
            ("key0", "value0"),
            ("key1", "value1"),
            ("key2", "value2")
        ]

        var dataEntries = [PieChartDataEntry]()
        for i in 0..<summeryList.count {
            let dataEntry = PieChartDataEntry(value: summeryList[i].1, label: summeryList[i].0)
            dataEntries.append(dataEntry)
        }
        let dataSet = PieChartDataSet(values: dataEntries, label: "ラベル")
        let data = PieChartData(dataSet: dataSet)

        pieChartView.data = data
    }

    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {

        if let dataSet = pieChartView.data?.dataSets[highlight.dataSetIndex] {

            let sliceIndex: Int = dataSet.entryIndex(entry: entry)
            let label = summeryList[sliceIndex].0
            let value = summeryList[sliceIndex].1
    }
}

ポイントは以下。
ChartViewDelegate プロトコルを追加
chartValueSelected 関数をサポート
chartValueSelected の引数からタップした部分の値を取得する方法

ちなみに本記事は、Charts 3.0 での処理です。
ググると古いバージョンの記事が多くて、Charts 3.0 で使えるコードを探し出すのに苦労したので書きました。

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8