對(duì)于charts的基本用法,百度即可,本文講解兩個(gè)關(guān)鍵點(diǎn)代碼,參考蠟狀圖用以下兩個(gè)實(shí)例來(lái)進(jìn)行講解。
先上實(shí)例圖:

蠟狀圖的使用類是CombinedChartView,當(dāng)我們?cè)谏厦孢M(jìn)行點(diǎn)擊時(shí),charts會(huì)給生成默認(rèn)的十字樣式,當(dāng)你去查看的時(shí)候,你會(huì)發(fā)現(xiàn)有一個(gè)highlighter屬性,來(lái)決定此十字樣式的生成或隱藏,如果沒有深層了解,都無(wú)法清楚其如何產(chǎn)生,k線生成使用重繪方式【draw(_rect:CGRect) 與?setNeedsDisplay()結(jié)合】來(lái)渲染成圖片。
實(shí)例1,觸摸點(diǎn)顯示十字樣式
詳解: 創(chuàng)建一個(gè)類CustomCombinedChartView:CombinedChartView,同時(shí)定義一個(gè)協(xié)議protocol?CustomChartViewTapDelegate: ChartViewDelegate;
CustomCombinedChartView內(nèi)部自定義tap手勢(shì)覆蓋charts的tap手勢(shì),手勢(shì)綁定的事件方法內(nèi)部實(shí)現(xiàn):
...
var?pt = recognizer.location(in:self)
///此句是關(guān)鍵代碼,&pt是因?yàn)榇颂幱衖nout定義,傳入的是數(shù)據(jù)實(shí)體,改變的也是數(shù)據(jù)本身,并非索引
getTransformer(forAxis: .left).pixelToValues(&pt)
customDelegate.customChartTapAction!(chartView:self, gestrue: recognizer, selectedIndex:Int(round(pt.x)))
...
CustomChartViewTapDelegate協(xié)議內(nèi)部實(shí)現(xiàn)以下方法,傳送CustomCombinedChartView實(shí)例和tap手勢(shì)實(shí)例
...code
func?customChartTapAction(chartView:ChartViewBase, gestrue:UITapGestureRecognizer, selectedIndex:Int)
...
此方法是在外部使用CustomCombinedChartView的時(shí)候,需要添加十字樣式時(shí)遵循實(shí)現(xiàn)。
想要獲取觸摸點(diǎn)的在蠟狀圖中對(duì)應(yīng)的k線坐標(biāo)值,可以通過(guò)以下代碼:
...
? ? ? ? ? ? pt = gestrue.location(in:lineChart)
? ? ? ? ? ? let?value = lineChart.valueForTouchPoint(point: pt, axis: .left).y
? ? ? ? ? ? value即是坐標(biāo)值
...
2,添加最新數(shù)據(jù)收盤標(biāo)簽(即是圖中深藍(lán)色背景的):
承上:
在CustomCombinedChartView內(nèi)部定義一個(gè)接收最后一條收盤數(shù)據(jù)的double屬性close,
重寫draw(_rect:CGRect)方法,簡(jiǎn)單實(shí)現(xiàn)如下:
...
overridefunc?draw(_rect:CGRect) {
? ? ? ? super.draw(rect)
// 此y值即是k線圖數(shù)值轉(zhuǎn)化后的視圖UI坐標(biāo)
? ? ? ? let?y =pixelForValues(x:0, y: close, axis: .right).y
? ? }
...
3,小點(diǎn)子
(1)使蠟狀圖右部縱軸對(duì)齊的方式【紅色框即是】:?
rightAxis.enabled = true // 顯示此右側(cè)坐標(biāo)軸
rightAxis.maxWidth = 50
rightAxis.minWidth = 50
(2) 縱坐標(biāo)保留6位有效數(shù)字:
...
? ??????let?numberForm = NumberFormatter()
? ? ? ? numberForm.minimumIntegerDigits = 1
? ? ? ? numberForm.generatesDecimalNumbers = true
? ? ? ? numberForm.maximumSignificantDigits = 6
? ? ? ? letaxisFormatter =DefaultAxisValueFormatter(formatter: numberForm)
? ? ? ? rightAxis.valueFormatter = axisFormatter
...
謝謝閱讀