如何在 Swift3 IOS 饼图中添加点击手势识别?

How to add tap gesture recognition in Swift3 IOS Pie chart?

我正在使用 Swift 开发小练习 IOS 应用程序 3. 在该应用程序中,我想要一个饼图。为了构建饼图,我遵循了 this link 并生成了饼图。

现在我想再添加一项功能。当用户像任何一个月一样点击饼图的某个区域时,它应该会打开一个新的控制器并仅显示该月的详细信息。

我设法添加了手势识别功能。但是当我点击屏幕的任何部分时,它会打开新屏幕。我只想将该点击功能限制为饼图部分,并且应该捕获该饼图月份。代码是

let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))

pieChartView.addGestureRecognizer(gestureRecognizer)

处理点击代码是

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)

}

感谢任何帮助!!

============================

更新代码

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) ")
    }

}

查看Appcoda tutorial中的Touch Events部分,找到ChartViewDelegate方法chartValueSelected,所以需要使用该方法而不是 UITapGestureRecognizer.

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
     print("\(entry.value) in \(yourArray[entry.xIndex])")
}

handleTap 中,使用手势识别器的 locationInView 来确定点击在图表的哪个部分(如果有),并做出相应的响应。