金額計算的部分,在前一篇就完成了,這一篇開始講 pie chart 的實作。
分析我們要做的事情
1 - 設置 Pie Chart View 的基本 UI
// MARK: ui methods
private func setup(chartView: PieChartView) {
chartView.usePercentValuesEnabled = true
chartView.drawSlicesUnderHoleEnabled = false
chartView.holeRadiusPercent = 0.58
chartView.transparentCircleRadiusPercent = 0.61
chartView.chartDescription?.enabled = false
chartView.setExtraOffsets(left: 5, top: 10, right: 5, bottom: 5)
chartView.drawCenterTextEnabled = true
chartView.drawHoleEnabled = false
chartView.rotationEnabled = true
chartView.highlightPerTapEnabled = true
chartView.entryLabelColor = .darkText
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .top
l.orientation = .vertical
l.drawInside = false
l.xEntrySpace = 7
l.yEntrySpace = 0
l.yOffset = 0
l.textColor = .black
// chartView.legend = l
}
2 - 依最新的三大法人資訊日期為 key,找出對應 key 的當日台股成交量
/// 獲得當下三大法人日期的大盤資訊
private func getMarketTradingInfo() -> TwMarketTradingInfo? {
let timeInterval = date.timeIntervalSince1970
for info in dailyTradingInfo {
if info.date.timeIntervalSince1970 == timeInterval {
return info
}
}
return nil
}
3 - 依照台股成交量計算三大法人成交比重
4 - 將成交比重的值轉成 PieChartData
在第 3 步要注意的是,getPieChartData 傳進來的值是 [買進 + 賣出] 的值,但比重的計算上,應該是 [買進 + 賣出] / 2 才是合理的。因為台股總成交金額 == 總買進金額 == 總賣出金額,所以要相加除以2。
private func getPieChartData(threeMajorTrading: Double, twMarketTrading: Double) -> PieChartData {
// 三大法人傳入值是加總,所以要除以台股總成交後,再除以 2
let threeMajorPercentage = (threeMajorTrading / twMarketTrading) / 2
let nonThreeMajorPercentage = 1 - threeMajorPercentage
let threeMajorTradingData = PieChartDataEntry(value: threeMajorPercentage, label: "三大法人交易額")
let nonThreeMajorTradingData = PieChartDataEntry(value: nonThreeMajorPercentage, label: "非三大法人交易額")
let dataSet = PieChartDataSet(entries: [threeMajorTradingData, nonThreeMajorTradingData])
dataSet.colors = [.systemGreen, .systemBlue]
let data = PieChartData(dataSet: dataSet)
data.setValueTextColor(.darkText)
return data
}
5 - 呼叫上列所有 func 並渲染 pie chart view
/// 計算三大法人佔股市交易的額度
private func updatePieChartThreeMajorPercentage() {
guard let twMarketTradingInfo = getMarketTradingInfo(),
let threeMajor = totalMajorInvestorInfo?.total else {
print("找不到和三大法人同日的大盤成交資訊,請檢查資料來源")
return
}
let threeMajorTrading = threeMajor.totalBuy + threeMajor.totalSell
let twMarketTrading = twMarketTradingInfo.value ?? 0
let data = getPieChartData(threeMajorTrading: threeMajorTrading, twMarketTrading: twMarketTrading)
pieChartView.data = data
}
最後,讓這些 func 在 button 中發動
@IBAction func drawPieChartButtonDidTap(_ sender: Any) {
setup(chartView: self.pieChartView)
updatePieChartThreeMajorPercentage()
}
完成這一步的 UI 如下
台股申購日曆
IT鐵人賽Demo App
下方是這次 D1 ~ D12 的完成品,可以下載來試
App Store - 台股申購日曆