I am in mid of developing small practice IOS app using Swift 3. Inside that app, I would like to have a Pie chart. To build a Pie chart, I followed this link and pie chart is getting generated.
Now I want to add one more functionality. When user tap on one of the area of Pie chart like any month, then it should open a new controller and display details of that month only.
I managed to add gesture recognition functionality. But when I tap any portion of the screen, it opens up the new screen. I want to limit that tap functionality to Pie chart section only and that Pie chart month should be captured. The code is
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))
pieChartView.addGestureRecognizer(gestureRecognizer)
And handle tap code is
func handleTap(gestureRecognizer: UIGestureRecognizer) {
let monthDetail = storyboard?.instantiateViewController(withIdentifier: "MonthTableView") as! MonthDetailsTableViewController
monthDetail = month //Should be the month value of Tap area
navigationController?.pushViewController(monthDetail, animated: true)
}
Appreciate any help!!
==========================
import UIKit
import Charts
import CoreData
class ExpenseViewController: UIViewController, ChartViewDelegate {
@IBOutlet weak var pieChartView: PieChartView!
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
var unitsSold = [10.0, 20.0, 10.0, 30.0, 10.0, 10.0]
override func viewDidLoad() {
super.viewDidLoad()
setChart(dataPoints: months, values: unitsSold)
pieChartView.delegate = self
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = PieChartDataEntry(value: values[i], label: dataPoints[i])
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Units Sold")
let pieChartData = PieChartData(dataSet: pieChartDataSet)
pieChartView.data = pieChartData
}
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlighter) {
//print("\(entry.value) in \(months[entry.xIndex])")
print("Y = \(entry.y) ")
print("X = \(entry.x) ")
}
}
Check the Touch Events part in your Appcoda tutorial, you find the ChartViewDelegate
method chartValueSelected
, so you need to use that method instead of UITapGestureRecognizer
.
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
print("\(entry.value) in \(yourArray[entry.xIndex])")
}