Charts 是iOS中比較強大的圖表開源庫,使用的Swift 開發(Obj-c專案也可以使用),支持餅圖(PieChart)、折線圖(線狀圖)、柱狀圖(BarChart),以及股票圖(CandleStickChart)等多種圖表,并能漸變填充和影片加載以及自定義,具體可參考官網:https://github.com/danielgindi/Charts,其中CombinedChartView混合圖表非常實用,可以使用任意圖表混合搭配,實作股票蠟燭圖(也支持西方的行情圖)和相應指標圖形,效果圖參考如下:

效果圖中主要實作以下了幾個功能:
1、主行情圖及MA、BOLL指標圖影片加載,縮放、滑動
2、副圖MACD、KDJ指標圖影片加載,縮放、滑動
3、自定義十字線及其主副圖選中值獲取
4、指標切換
現將主要參考代碼列出如下:
一、定義行情主副圖表以及相應屬性設定
import Charts
/// 混合主股票蠟燭圖
private lazy var combineLineStickChart:CombinedChartView = {[weak self] in
autoreleasepool {
let _stChartView = CombinedChartView.init()
//縮放樣式
MarketSetting.setZoomStyleFor(Chart: _stChartView)
//空視圖樣式
MarketSetting.setEmptyStyleFor(Chart: _stChartView)
//右邊刻度樣式
MarketSetting.setRightCalibrationStyleFor(Chart: _stChartView, andShowCount: 7)
//底部橫軸樣式
MarketSetting.setBottomCalibrationStyleFor(Chart: _stChartView,
andIsShow: true,
withShowCount: 3)
//整體樣式
MarketSetting.setGradStyleFor(Chart: _stChartView,
withEdgeInsets: .init(top: 10, left: 10, bottom: 0, right: 0),
andDelegate:self)
return _stChartView
}
}()
/// 混合副圖指標
private lazy var combineLineChare:CombinedChartView = {[weak self] in
autoreleasepool {
let _ccv = CombinedChartView.init()
//設定影片時間
_ccv.animate(xAxisDuration:MarketSetting.timeInterval)
//整體樣式
MarketSetting.setGradStyleFor(Chart: _ccv,
withEdgeInsets: .init(top: 0, left: 10, bottom: 0, right: 1.5),
andDelegate:self)
//底部橫軸樣式
MarketSetting.setBottomCalibrationStyleFor(Chart: _ccv,
andIsShow: false,
withShowCount: 0)
//縮放樣式
MarketSetting.setZoomStyleFor(Chart: _ccv)
//空視圖樣式
MarketSetting.setEmptyStyleFor(Chart: _ccv)
//右邊刻度樣式
MarketSetting.setRightCalibrationStyleFor(Chart: _ccv, andShowCount: 3)
return _ccv
}
}()
屬性設定及描述參考:
/// 行情樣式設定
struct MarketSetting {
/// 副圖指標資料
static var dicKpiData = [String:[Double]]()
/// 主圖指標資料
static var dicKpiMainData = [String:[Double]]()
/// 十字線顏色
static let highlightColor = UIColor.lightGray
/// 右邊刻度顏色
static let labelRightTextColor = UIColor.black
/// 右邊刻度字體大小
static let labelRightFont = UIFont.systemFont(ofSize: 10)
/// 影片時間
static let timeInterval = TimeInterval.init(1.5)
/// 紅漲
static let red_color:UIColor = UIColor.init().colorFromHexInt(hex: 0xF5324D)
/// 綠跌
static let greent_color:UIColor = UIColor.init().colorFromHexInt(hex: 0x2DB476)
/// dif 顏色
static let dif_color:UIColor = UIColor.init(hexString: "#E6B970")!
/// dea 顏色
static let dea_color:UIColor = UIColor.init(hexString: "#4C6E9C")!
/// macd 顏色
static let kacd_color:UIColor = UIColor.purple
/// 其他
static let kother_color:UIColor = UIColor.brown
/// 比率
static let right_ratio:Double = 1.5 / 288
/// 副圖指標
static let arrMinorKPI = ["MACD","KDJ"]
/// 主圖指標
static let arrMainKPI = ["MA","BOLL"]
/// 副圖當前指標索引
static var minorCurrentIndex:Int = 0
/// 主圖當前指標索引
static var mainCurrentIndex:Int = 0
}
//MARK: -
/// 行情相關設定
extension MarketSetting {
/// 設定縮放樣式
/// - Parameter chart: BarLineChartViewBase
static func setZoomStyleFor(Chart chart:BarLineChartViewBase){
//縮放
chart.scaleXEnabled = true
chart.scaleYEnabled = false
//自動縮放
chart.autoScaleMinMaxEnabled = false
chart.highlightPerTapEnabled = true
//高亮拖拽
chart.highlightPerDragEnabled = true
//手勢捏合
chart.pinchZoomEnabled = false
//開啟拖拽
chart.dragEnabled = true
//0 1 慣性
chart.dragDecelerationFrictionCoef = 0.95
//最大縮放值 最小縮放值 y軸不縮放 minScl maxScl根據實際情況調整
chart.setScaleMinima(5, scaleY: 1)
//最大縮放級別
chart.viewPortHandler.setMaximumScaleX(20)
//是否顯示圖例
chart.legend.enabled = false
//禁止雙擊縮放 有需要可以設定為YES
chart.doubleTapToZoomEnabled = false
//最大顯示數(兩者搭配使用)
chart.maxVisibleCount = 30
}
/// 設定空視圖樣式
/// - Parameter chart: BarLineChartViewBase
static func setEmptyStyleFor(Chart chart:BarLineChartViewBase) {
//[S]暫無資料
chart.noDataText = "暫無資料"
chart.noDataTextAlignment = .center
chart.noDataTextColor = UIColor.lightGray
chart.noDataFont = UIFont.systemFont(ofSize: 15)
//[E]
}
/// 設定右邊縱軸刻度樣式
/// - Parameters:
/// - chart: BarLineChartViewBase
/// - c: 展示刻度數
static func setRightCalibrationStyleFor(Chart chart:BarLineChartViewBase,
andShowCount c:Int) {
//[S]設定y軸相關引數 將坐標軸顯示在右邊
let rightAxi:YAxis = chart.rightAxis
rightAxi.enabled = true
//保留兩位小數
rightAxi.decimals = 2
//設定顯示最大點數
rightAxi.labelCount = c
//強制label個數
rightAxi.forceLabelsEnabled = false
rightAxi.drawGridLinesEnabled = true
rightAxi.drawAxisLineEnabled = false
//內邊框
rightAxi.gridLineDashLengths = [5.0, 5.0]
rightAxi.gridLineDashPhase = 0
//label位置
rightAxi.labelPosition = .outsideChart
//文字顏色
rightAxi.labelTextColor = MarketSetting.labelRightTextColor
//文字字體
rightAxi.labelFont = MarketSetting.labelRightFont
//[E]
//左邊刻度
chart.leftAxis.enabled = false
}
/// 設定左邊縱軸刻度樣式
/// - Parameters:
/// - chart: BarLineChartViewBase
/// - c: 展示刻度數
static func setLeftCalibrationStyleFor(Chart chart:BarLineChartViewBase,
andShowCount c:Int) {
//[S]設定y軸相關引數 將坐標軸顯示在右邊
let leftAxi:YAxis = chart.leftAxis
leftAxi.enabled = true
//保留兩位小數
leftAxi.decimals = 2
//設定顯示最大點數
leftAxi.labelCount = c
//強制label個數
leftAxi.forceLabelsEnabled = false
leftAxi.drawGridLinesEnabled = true
leftAxi.drawAxisLineEnabled = false
//內邊框
leftAxi.gridLineDashLengths = [5.0, 5.0]
leftAxi.gridLineDashPhase = 0
//label位置
leftAxi.labelPosition = .outsideChart
//文字顏色
leftAxi.labelTextColor = MarketSetting.labelRightTextColor
//文字字體
leftAxi.labelFont = MarketSetting.labelRightFont
//[E]
//左邊刻度
chart.rightAxis.enabled = false
}
/// 設定底部橫軸樣式
/// - Parameters:
/// - chart: BarLineChartViewBase
/// - show: true 顯示刻度 防止不顯示
/// - c: 顯示刻度條數
static func setBottomCalibrationStyleFor(Chart chart:BarLineChartViewBase,
andIsShow show:Bool,
withShowCount c:Int) {
//設定X軸相關引數
chart.xAxis.enabled = show
chart.xAxis.labelPosition = .bottom
chart.xAxis.labelCount = c
chart.xAxis.drawGridLinesEnabled = false
chart.xAxis.drawAxisLineEnabled = true
//避免文字顯示不全 這個屬性很重要
chart.xAxis.avoidFirstLastClippingEnabled = true
//第一個和最后一個圖會顯示一半(顯示不全)
chart.xAxis.spaceMin = 0.5
chart.xAxis.spaceMax = 0.5
//強制label個數
chart.xAxis.forceLabelsEnabled = false
//設定重復不顯示
chart.xAxis.granularityEnabled = true
//間距
chart.xAxis.granularity = 1
}
/// 設定背景、邊框等樣式
/// - Parameters:
/// - chart: BarLineChartViewBase
/// - sgbg: true 顯示背景
/// - bgc: 背景色
/// - sb: true 顯示邊框
/// - bdc: 邊框背景
/// - edg: UIEdgeInsets 偏移(防止靠邊沒顯示全)
static func setGradStyleFor(Chart chart:BarLineChartViewBase,
andShowGridBackground sgbg:Bool = false,
withBGColor bgc:UIColor = UIColor.clear,
andShowBorders sb:Bool = false,
andBorderColor bdc:UIColor = UIColor.clear,
withEdgeInsets edg:UIEdgeInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10),
andDelegate _delegate:ChartViewDelegate? = nil) {
//是否顯示氣泡
chart.drawMarkers = false
chart.delegate = _delegate
//畫板以及邊框顏色
chart.gridBackgroundColor = bgc
chart.borderColor = bdc
//根據需要顯示或隱藏邊框以及畫板
chart.drawGridBackgroundEnabled = sgbg
chart.drawBordersEnabled = sb
chart.backgroundColor = bgc
//設定偏移
chart.setExtraOffsets(left: edg.left,
top: edg.top,
right: edg.right,
bottom: edg.bottom)
//描述文字
chart.chartDescription?.enabled = false
}
/// 設定股票資料源
/// - Parameter yv: [ChartDataEntry]
/// - Returns: CandleChartDataSet
static func setStockDataSetFor(Values yv:[ChartDataEntry]) -> CandleChartDataSet {
let dataSet = CandleChartDataSet.init(entries: yv, label: nil)
//軸線方向
dataSet.axisDependency = .right
//不在面板上直接顯示數值
dataSet.drawValuesEnabled = false
//true 蠟燭圖 false 美國線
dataSet.showCandleBar = true
//k線柱間隙
dataSet.barSpace = 0.1
//這是用于顯示最高最低值區間的立線
//dataSet.shadowColor = UIColor.black
//立線的寬度
dataSet.shadowWidth = 0.7
dataSet.shadowColorSameAsCandle = true
// close >= open 紅漲
dataSet.increasingColor = red_color
dataSet.neutralColor = red_color
// 內部是否充滿顏色
dataSet.increasingFilled = true
// open > close 綠跌
dataSet.decreasingColor = greent_color
// 內部是否充滿顏色
dataSet.decreasingFilled = true
//十字線
dataSet.drawHorizontalHighlightIndicatorEnabled = false
dataSet.drawVerticalHighlightIndicatorEnabled = false
dataSet.highlightEnabled = true
return dataSet
}
/// 設定LineChartDataSet
/// - Parameters:
/// - yv: [ChartDataEntry]
/// - c: 線條顏色
/// - n: 線條名稱
/// - Returns: LineChartDataSet
static func setLineDataFor(Values yv:[ChartDataEntry],
andColor c:UIColor,
withName n:String) -> LineChartDataSet {
//創建LineChartDataSet物件
let picketageSet = LineChartDataSet.init(entries: yv, label: n)
//不在面板上直接顯示數值
picketageSet.drawValuesEnabled = false
//十字線
picketageSet.drawHorizontalHighlightIndicatorEnabled = false
picketageSet.drawVerticalHighlightIndicatorEnabled = false
picketageSet.highlightEnabled = false
//十字線高亮顏色
picketageSet.highlightColor = highlightColor
//線條顏色
picketageSet.setColor(c)
//沒有圓圈
picketageSet.circleRadius = 0.0
picketageSet.circleHoleRadius = 0.0
return picketageSet
}
/// 設定柱狀圖資料
/// - Parameters:
/// - yv: [ChartDataEntry]
/// - n: 名稱
/// - Returns: BarChartDataSet
static func setBarCharSetFor(Values yv:[ChartDataEntry],
withName n:String) -> BarChartDataSet {
let barChartDataSet = MyBarChartDataSet.init(entries: yv, label: n)
barChartDataSet.axisDependency = .left
barChartDataSet.setColors(red_color,greent_color)
//不在面板上直接顯示數值
barChartDataSet.drawValuesEnabled = false
barChartDataSet.drawIconsEnabled = false
return barChartDataSet
}
/// 設定柱狀圖
/// - Parameter yv: [ChartDataEntry]
/// - Returns: BarChartData
static func setBarDataSetsFor(Values yv:[BarChartDataEntry]) -> [BarChartDataSet] {
var arrTemp = [BarChartDataSet]()
for item in yv {
//創建BarChartDataSet物件
let picketageSet = BarChartDataSet.init(entries: [item], label: nil)
//不在面板上直接顯示數值
picketageSet.drawValuesEnabled = false
//是否顯示十字線
picketageSet.highlightEnabled = true
arrTemp.append(picketageSet)
}
return arrTemp
}
}
二、主行情圖及MA、BOLL指標圖資料系結及影片加載
//MARK: - 主圖資料系結
extension MainView {
/// 主圖資料系結
/// - Parameter isChange: Bool
private func setMainCombineLineData(isChange:Bool = false) {
if self.arrChartData.count <= 0 { return }
//MARK:X軸資料
var i = 0
var xValues = [String]()
var yStockValue = [ChartDataEntry]()
for item in self.arrChartData {
let _dateTime:UInt32 = item["UpdateTime"] as! UInt32
let _strDateTime = Utils.shareInstance().getDateTimeForUnix(unixTime: _dateTime, strFormat: "MM/dd HH:mm")
xValues.append(_strDateTime)
let entry = CandleChartDataEntry.init(x: Double.init(i),
shadowH: Double.init("\(item["High"] ?? "0.000")")!,
shadowL: Double.init("\(item["Low"] ?? "0.000")")!,
open: Double.init("\(item["Open"] ?? "0.000")")!,
close: Double.init("\(item["Close"] ?? "0.000")")!)
yStockValue.append(entry)
i += 1
}
if xValues.count > 0 {
self.combineLineStickChart.xAxis.valueFormatter = IndexAxisValueFormatter.init(values: xValues)
self.combineLineChare.xAxis.valueFormatter = IndexAxisValueFormatter.init(values: xValues)
}
//MARK:MA
if MarketSetting.mainCurrentIndex == 0 {
MarketSetting.dicKpiMainData = [
MA.kpiType.ma5.rawValue : MA.init().calcMA(Data: self.arrChartData, andNmbner: 5),
MA.kpiType.ma10.rawValue : MA.init().calcMA(Data: self.arrChartData, andNmbner: 10),
MA.kpiType.ma15.rawValue : MA.init().calcMA(Data: self.arrChartData, andNmbner: 15),
MA.kpiType.ma30.rawValue : MA.init().calcMA(Data: self.arrChartData, andNmbner: 30),
]
guard let(_arrMA5,_arrMA10,_arrMA15,_arrMA30) = (MarketSetting.dicKpiMainData[MA.kpiType.ma5.rawValue],
MarketSetting.dicKpiMainData[MA.kpiType.ma10.rawValue],
MarketSetting.dicKpiMainData[MA.kpiType.ma15.rawValue],
MarketSetting.dicKpiMainData[MA.kpiType.ma30.rawValue]) as? (
[Double],[Double],[Double],[Double]) else {
return
}
self.setMainKpiDataFor(Values1: _arrMA5,
Values2: _arrMA10,
Values3: _arrMA15,
Values4: _arrMA30,
withYStockValue: yStockValue,
andisChange: isChange)
}
//MARK:BOLL
else if MarketSetting.mainCurrentIndex == 1 {
MarketSetting.dicKpiMainData = BOLL.init().calcBOLLFor(Data: self.arrChartData, andNumber: 26, withP: 2)
guard let(_arrUp,_arrMid,_arrLow) = (MarketSetting.dicKpiMainData[BOLL.kpiType.up.rawValue],
MarketSetting.dicKpiMainData[BOLL.kpiType.mid.rawValue],
MarketSetting.dicKpiMainData[BOLL.kpiType.low.rawValue]) as? (
[Double],[Double],[Double]) else {
return
}
self.setMainKpiDataFor(Values1: _arrUp,
Values2: _arrMid,
Values3: _arrLow,
withYStockValue: yStockValue,
andisChange: isChange)
}
}
private func setMainKpiDataFor(Values1 _arrV1:[Double],
Values2 _arrV2:[Double],
Values3 _arrV3:[Double],
Values4 _arrV4:[Double]? = nil,
withYStockValue yStockValue:[ChartDataEntry] = [ChartDataEntry](),
andisChange isChange:Bool = false){
var yV1 = [ChartDataEntry]()
var yV2 = [ChartDataEntry]()
var yV3 = [ChartDataEntry]()
var yV4 = [ChartDataEntry]()
//V1
let _count = self.arrChartData.count
var minIndex = self.arrChartData.count - _arrV1.count
for i in minIndex..<_count {
let entry = ChartDataEntry.init(x: Double.init(i),y: _arrV1[i - minIndex])
yV1.append(entry)
}
//V2
minIndex = self.arrChartData.count - _arrV2.count
for i in minIndex..<_count {
let entry = ChartDataEntry.init(x: Double.init(i),y: _arrV2[i - minIndex])
yV2.append(entry)
}
//V3
minIndex = self.arrChartData.count - _arrV3.count
for i in minIndex..<_count {
let entry = ChartDataEntry.init(x: Double.init(i),y: _arrV3[i - minIndex])
yV3.append(entry)
}
//V4
if _arrV4 != nil {
minIndex = self.arrChartData.count - _arrV4!.count
for i in minIndex..<_count {
let entry = ChartDataEntry.init(x: Double.init(i),y: _arrV4![i - minIndex])
yV4.append(entry)
}
}
//設定資料
let data:CombinedChartData = CombinedChartData.init()
let ds = [
MarketSetting.setLineDataFor(Values: yV1,andColor: MarketSetting.dif_color,withName: ""),
MarketSetting.setLineDataFor(Values: yV2,andColor: MarketSetting.dea_color,withName: ""),
MarketSetting.setLineDataFor(Values: yV3,andColor: MarketSetting.kacd_color,withName: ""),
]
if _arrV4 != nil {
MarketSetting.setLineDataFor(Values: yV4, andColor: MarketSetting.kother_color,withName:"")
}
data.lineData = LineChartData.init(dataSets: ds)
//股票
data.candleData = CandleChartData.init(dataSets:[
MarketSetting.setStockDataSetFor(Values: yStockValue)
])
self.combineLineStickChart.data = data
if isChange {
self.combineLineStickChart.animate(xAxisDuration: MarketSetting.timeInterval)
}
if let _xMax = self.combineLineStickChart.data?.xMax {
//開局移動到最右邊xMax為最大x軸值
self.combineLineStickChart.moveViewToX(_xMax)
}
}
}
三、副圖MACD、KDJ指標圖數系結及影片加載
//MARK: - 副圖指標資料系結
extension MainView {
/// 指標圖資料系結
/// - Parameter isChange: isChange description
private func setCombineLineData (isChange:Bool = false,
andIndex ix:Int = 0){
//副圖指標資料
if self.arrChartData.count > 0 {
//MARK:MACD
if ix == 0 {
MarketSetting.dicKpiData = MACD.init().calcMACDFor(Data: self.arrChartData)
guard let(_arrDif,_arrDea,_arrMACD) = (
MarketSetting.dicKpiData[MACD.kpiType.dif.rawValue],
MarketSetting.dicKpiData[MACD.kpiType.dea.rawValue],
MarketSetting.dicKpiData[MACD.kpiType.macd.rawValue]) as? (
[Double],[Double],[Double]) else {
return
}
self.setMACDFor(DIF: _arrDif, andDEA: _arrDea, andMACD: _arrMACD,withChange: isChange)
}
//MARK:KDJ
else if ix == 1 {
MarketSetting.dicKpiData = KDJ.init().calcKDJFor(Data: self.arrChartData,andNumber: 9,andK: 3,withD: 3)
guard let(_arrK,_arrD,_arrJ) = (
MarketSetting.dicKpiData[KDJ.kpiType.k.rawValue],
MarketSetting.dicKpiData[KDJ.kpiType.d.rawValue],
MarketSetting.dicKpiData[KDJ.kpiType.j.rawValue]) as? (
[Double],[Double],[Double]) else {
return
}
self.setKDJFor(K: _arrK, andD: _arrD, andJ: _arrJ, withChange: isChange)
}
}
}
private func setMACDFor(DIF _arrDif:[Double],
andDEA _arrDea:[Double],
andMACD _arrMACD:[Double],
withChange isChange:Bool){
var yDIFValues = [ChartDataEntry]()
var yDEAValues = [ChartDataEntry]()
var yMACDValues = [ChartDataEntry]()
//DIF
for i in 0..<_arrDif.count {
let entry = ChartDataEntry.init(x: Double.init(i),
y: _arrDif[i])
yDIFValues.append(entry)
}
//DEA
for i in 0..<_arrDea.count {
let entry = ChartDataEntry.init(x: Double.init(i),
y: _arrDea[i])
yDEAValues.append(entry)
}
//MACD
for i in 0..<_arrMACD.count {
let entry = BarChartDataEntry.init(x: Double.init(i), y: _arrMACD[i])
yMACDValues.append(entry)
}
//設定資料
let data:CombinedChartData = CombinedChartData.init()
//DIF,DEA
let lineDS = LineChartData.init(dataSets: [
MarketSetting.setLineDataFor(Values: yDIFValues,
andColor: MarketSetting.dif_color,
withName: "DIF"),
MarketSetting.setLineDataFor(Values: yDEAValues,
andColor: MarketSetting.dea_color,
withName: "DEA")])
data.lineData = lineDS
//MACD
data.barData = BarChartData.init(dataSets: [
MarketSetting.setBarCharSetFor(Values: yMACDValues, withName: "MACD")
])
self.combineLineChare.data = data
if isChange {
self.combineLineChare.animate(xAxisDuration: MarketSetting.timeInterval)
}
if let _xMax = self.combineLineChare.data?.xMax {
//開局移動到最右邊xMax為最大x軸值
self.combineLineChare.moveViewToX(_xMax)
}
}
private func setKDJFor(K _arrK:[Double],
andD _arrD:[Double],
andJ _arrJ:[Double],
withChange isChange:Bool){
var yKValues = [ChartDataEntry]()
var yDValues = [ChartDataEntry]()
var yJValues = [ChartDataEntry]()
//K
for i in 0..<_arrK.count {
let entry = ChartDataEntry.init(x: Double.init(i),
y: _arrK[i])
yKValues.append(entry)
}
//D
for i in 0..<_arrD.count {
let entry = ChartDataEntry.init(x: Double.init(i),
y: _arrD[i])
yDValues.append(entry)
}
//J
for i in 0..<_arrJ.count {
let entry = BarChartDataEntry.init(x: Double.init(i),
y: _arrJ[i])
yJValues.append(entry)
}
//設定資料
let data:CombinedChartData = CombinedChartData.init()
let lineDS = LineChartData.init(dataSets: [
MarketSetting.setLineDataFor(Values: yKValues,
andColor: MarketSetting.dif_color,
withName: "K"),
MarketSetting.setLineDataFor(Values: yDValues,
andColor: MarketSetting.dea_color,
withName: "D"),
MarketSetting.setLineDataFor(Values: yJValues,
andColor: MarketSetting.kacd_color,
withName: "J"),
])
data.lineData = lineDS
self.combineLineChare.data = data
if isChange {
self.combineLineChare.animate(xAxisDuration: MarketSetting.timeInterval)
}
if let _xMax = self.combineLineChare.data?.xMax {
//開局移動到最右邊xMax為最大x軸值
self.combineLineChare.moveViewToX(_xMax)
}
}
}
四、自定義十字線及其主副圖選中值獲取
//十字線
self.addSubview(self.labVerticalLine)
self.addSubview(self.labHorizontalLine)
self.addSubview(self.labHorizontalRight)
//添加手勢
let longGest = UILongPressGestureRecognizer.init(target: self, action: #selector(longGestAction(sender:)))
longGest.minimumPressDuration = TimeInterval.init(1.0)
self.addGestureRecognizer(longGest)
/// 垂直線
private lazy var labVerticalLine:YYLabel = {
autoreleasepool {
let _line = BaseView.createLable(rect: .zero,
text: nil,
textColor: nil,
font: nil,
backgroundColor:MarketSetting.highlightColor)
_line.isHidden = true
return _line
}
}()
/// 水平線右邊值
private lazy var labHorizontalRight:YYLabel = {
autoreleasepool {
let _line = BaseView.createLable(rect: .zero,
text: "0.00",
textColor: UIColor.init().colorFromHexInt(hex: 0xffffff, alpha: 0.6),
font: UIFont.systemFont(ofSize: 10),
backgroundColor:MarketSetting.highlightColor)
_line.textAlignment = .left
_line.isHidden = true
return _line
}
}()
/// 水平線
private lazy var labHorizontalLine:YYLabel = {
autoreleasepool {
let _line = BaseView.createLable(rect: .zero,
text: nil,
textColor: nil,
font: nil,
backgroundColor:MarketSetting.highlightColor)
_line.isHidden = true
return _line
}
}()
十字線手勢處理:
//MARK: - 十字線(手勢)
extension MainView {
/// 長按手勢
/// - Parameter sender: UILongPressGestureRecognizer
@objc private func longGestAction(sender:UILongPressGestureRecognizer) {
let transPoint:CGPoint = sender.location(in: self.combineLineStickChart)
if transPoint.x > K_APP_WIDTH - 30 {
return
}
print(transPoint.x)
switch sender.state {
//MARK:開始
case .began:
let (_,_newPoint) = self.updatePositionFor(Point: transPoint)
self.labVerticalLine.center = .init(x: _newPoint.x, y: self.labVerticalLine.size.height * 0.5 + 10)
if transPoint.y >= self.combineLineStickChart.top && transPoint.y <= self.combineLineChare.bottom {
self.labHorizontalLine.center = .init(x: self.labHorizontalLine.width * 0.5 + 10, y: transPoint.y)
self.updateRightViewFor(Point: transPoint)
}
self.labHorizontalRight.isHidden = false
self.labHorizontalLine.isHidden = false
self.labVerticalLine.isHidden = false
self.bottomView.isHidden = false
self.topView.isHidden = false
self.btnMACDTitle.isHidden = true
self.btnMATitle.isHidden = true
break
//MARK:手勢改變
case .changed:
let (_m,_newPoint) = self.updatePositionFor(Point: transPoint)
if let _model = _m {
print(String.init(format: "o:%.2f,h:%.2f,l:%.2f,c:%.2f",_model.open,_model.high,_model.low,_model.close))
self.labOpen.text = String.init(format:"%.2f",_model.open)
self.labHeight.text = String.init(format:"%.2f",_model.high)
self.labLow.text = String.init(format:"%.2f",_model.low)
self.labClose.text = String.init(format:"%.2f",_model.close)
self.labVerticalLine.center = .init(x: _newPoint.x, y: self.labVerticalLine.size.height * 0.5 + 10)
if transPoint.y >= self.combineLineStickChart.top && transPoint.y <= self.combineLineChare.bottom {
self.labHorizontalLine.center = .init(x: self.labHorizontalLine.width * 0.5 + 10, y: transPoint.y)
self.updateRightViewFor(Point: transPoint)
}
//更新頂部
self.updateTopViewFor(Index: Int(_model.x))
//更新底部
self.updateBottomViewFor(Index: Int(_model.x))
}
break
//MARK:其他(取消、結束...)
default:
self.labHorizontalRight.isHidden = true
self.labHorizontalLine.isHidden = true
self.labVerticalLine.isHidden = true
self.bottomView.isHidden = true
self.topView.isHidden = true
self.btnMACDTitle.isHidden = false
self.btnMATitle.isHidden = false
break
}
}
/// 根據手勢移動的坐標獲取對應K線上的坐標
/// - Parameter p: CGPoint
/// - Returns: (CandleChartDataEntry?,CGPoint)
private func updatePositionFor(Point p:CGPoint) -> (CandleChartDataEntry?,CGPoint) {
let _model:CandleChartDataEntry? = self.combineLineStickChart.getEntryByTouchPoint(point: p) as? CandleChartDataEntry
var _newPoint = p
if _model != nil {
_newPoint = self.combineLineStickChart.getPosition(entry: _model!, axis: YAxis.AxisDependency.right)
}
return (_model,_newPoint)
}
//MARK:主圖指標值
/// 更新頂部主圖指標
/// - Parameter ix: Int
private func updateTopViewFor(Index ix:Int) {
if MarketSetting.mainCurrentIndex == 0 {
guard let(_arrMa5,_arrMa10,_arrMa15,_arrMa30) = (MarketSetting.dicKpiMainData[MA.kpiType.ma5.rawValue],MarketSetting.dicKpiMainData[MA.kpiType.ma10.rawValue],MarketSetting.dicKpiMainData[MA.kpiType.ma15.rawValue],MarketSetting.dicKpiMainData[MA.kpiType.ma30.rawValue]) as? ([Double],[Double],[Double],[Double]) else {
return
}
let _count = self.arrChartData.count
let _5Mindex = _count - _arrMa5.count
let _10Mindex = _count - _arrMa10.count
let _15Mindex = _count - _arrMa15.count
let _30Mindex = _count - _arrMa30.count
self.moveUpdateFor(View: self.topView,
andV1: (_arrMa5.count > (ix - _5Mindex) && (ix - _5Mindex) >= 0) ? String.init(format:"MA5:%.2f",_arrMa5[ix - _5Mindex]) : "MA5:0.00",
andV2: (_arrMa10.count > (ix - _10Mindex) && (ix - _10Mindex) >= 0) ? String.init(format:"MA10:%.2f",_arrMa10[ix - _10Mindex]) : "MA10:0.00",
withV3:(_arrMa15.count > (ix - _15Mindex) && (ix - _15Mindex) >= 0) ? String.init(format:"MA15:%.2f",_arrMa15[ix - _15Mindex]) : "MA15:0.00",
withV4: (_arrMa30.count > (ix - _30Mindex) && (ix - _30Mindex) >= 0) ? String.init(format:"MA30:%.2f",_arrMa30[ix - _30Mindex]) : "MA30:0.00")
}
else if MarketSetting.mainCurrentIndex == 1 {
guard let(_arrUp,_arrMid,_arrLow) = (MarketSetting.dicKpiMainData[BOLL.kpiType.up.rawValue],
MarketSetting.dicKpiMainData[BOLL.kpiType.mid.rawValue],MarketSetting.dicKpiMainData[BOLL.kpiType.low.rawValue]) as? ([Double],[Double],[Double]) else {
return
}
let _count = self.arrChartData.count
let _uMindex = _count - _arrUp.count
let _mMindex = _count - _arrMid.count
let _lMindex = _count - _arrLow.count
self.moveUpdateFor(View: self.topView,
andV1: (_arrUp.count > (ix - _uMindex) && (ix - _uMindex) >= 0) ? String.init(format:"UP:%.2f",_arrUp[ix - _uMindex]) : "UP:0.00",
andV2: (_arrMid.count > (ix - _mMindex) && (ix - _mMindex) >= 0) ? String.init(format:"MID:%.2f",_arrMid[ix - _mMindex]) : "MID:0.00",
withV3:(_arrLow.count > (ix - _lMindex) && (ix - _lMindex) >= 0) ? String.init(format:"LOW:%.2f",_arrLow[ix - _lMindex]) : "LOW:0.00",
withV4: nil)
}
}
//MARK:副圖指標值
/// 更新底部副圖指標
/// - Parameter ix: Int
private func updateBottomViewFor(Index ix:Int) {
if MarketSetting.minorCurrentIndex == 0 {
guard let(_arrDif,_arrDea,_arrMACD) = (MarketSetting.dicKpiData[MACD.kpiType.dif.rawValue],MarketSetting.dicKpiData[MACD.kpiType.dea.rawValue],MarketSetting.dicKpiData[MACD.kpiType.macd.rawValue]) as? ([Double],[Double],[Double]) else {
return
}
self.moveUpdateFor(View:self.bottomView,
andV1: _arrDif.count > ix ? String.init(format:"DIF:%.2f",_arrDif[ix]) : "DIF:0.00",
andV2: _arrDea.count > ix ? String.init(format:"DEA:%.2f",_arrDea[ix]) : "DEA:0.00",
withV3: _arrMACD.count > ix ? String.init(format:"MACD:%.2f",_arrMACD[ix]) : nil,
withV4: nil)
}
else if MarketSetting.minorCurrentIndex == 1 {
guard let(_arrK,_arrD,_arrJ) = (MarketSetting.dicKpiData[KDJ.kpiType.k.rawValue],MarketSetting.dicKpiData[KDJ.kpiType.d.rawValue],MarketSetting.dicKpiData[KDJ.kpiType.j.rawValue]) as? ([Double],[Double],[Double]) else {
return
}
self.moveUpdateFor(View:self.bottomView,
andV1: _arrK.count > ix ? String.init(format:"K:%.2f",_arrK[ix]) : "K:0.00",
andV2: _arrD.count > ix ? String.init(format:"D:%.2f",_arrD[ix]) : "D:0.00",
withV3: _arrJ.count > ix ? String.init(format:"J:%.2f",_arrJ[ix]) : nil,
withV4: nil)
}
}
private func moveUpdateFor(View v:UIView,
andV1 v1:String,
andV2 v2:String,
withV3 v3:String? = nil,
withV4 v4:String? = nil) {
var labV1:YYLabel?
var labV2:YYLabel?
var labV3:YYLabel?
var labV4:YYLabel?
for _view in v.subviews {
switch _view.tag {
case 1:
labV1 = _view as? YYLabel
case 2:
labV2 = _view as? YYLabel
case 3:
labV3 = _view as? YYLabel
v.viewWithTag(33)?.isHidden = v3 == nil ? true : false
case 4:
labV4 = _view as? YYLabel
v.viewWithTag(44)?.isHidden = v4 == nil ? true : false
default:
break
}
}
labV1?.text = v1
labV2?.text = v2
labV3?.text = v3
labV4?.text = v4
}
//MARK:十字線數值
/// 更新右邊水平十字線數值
/// - Parameter p: CGPoint
private func updateRightViewFor(Point p:CGPoint) {
self.labHorizontalRight.centerY = self.labHorizontalLine.centerY
var _min:Double = 0.0
var _max:Double = 0.0
var _unitValue:Double = 0.0
var _haveHight:CGFloat = 0.0
//匹配主圖刻度值
if p.y >= self.combineLineStickChart.top && p.y <= self.combineLineStickChart.bottom {
_min = self.combineLineStickChart.rightAxis.axisMinimum
_max = self.combineLineStickChart.rightAxis.axisMaximum
//計算單位高度的值
_unitValue = (_max - _min) / Double(self.combineLineStickChart.height)
//擁有的單位高度
_haveHight = p.y - self.combineLineStickChart.top
}
//匹配附圖刻度值
else if p.y >= self.combineLineChare.top && p.y <= self.combineLineChare.bottom {
_min = self.combineLineChare.rightAxis.axisMinimum
_max = self.combineLineChare.rightAxis.axisMaximum
//計算單位高度的值
_unitValue = (_max - _min) / Double(self.combineLineChare.height)
//擁有的單位高度
_haveHight = p.y - self.combineLineChare.top
}
//賦值
if _max > 0 {
self.labHorizontalRight.text = String.init(format:"%.2f",_max - _unitValue * Double(_haveHight))
}
}
}
五、主副圖表同步回應事件
//MARK: - ChartViewDelegate
extension MainView : ChartViewDelegate {
/// 圖表被移動(主、副圖同時回應)
/// https://blog.csdn.net/dianchidu6913/article/details/101228178
/// - Parameters:
/// - chartView: ChartViewBase
/// - dX: CGFloat
/// - dY: CGFloat
func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
self.updateTouchFor(ChartView: chartView)
}
/// 圖表被縮放
/// - Parameters:
/// - chartView: ChartViewBase
/// - scaleX: CGFloat
/// - scaleY: CGFloat
func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
self.updateTouchFor(ChartView: chartView)
}
/// 同步手勢
/// - Parameter chartView: chartView description
private func updateTouchFor(ChartView chartView:ChartViewBase){
let srcMatrix:CGAffineTransform = chartView.viewPortHandler.touchMatrix
self.combineLineStickChart.viewPortHandler.refresh(newMatrix: srcMatrix,
chart: self.combineLineStickChart,
invalidate: true)
self.combineLineChare.viewPortHandler.refresh(newMatrix: srcMatrix,
chart: self.combineLineChare,
invalidate: true)
}
}
由于篇幅有限指標計算以及原始碼和其他問題可留言咨詢獲取,相應引數設定見文中備注描述,
本文結束,歡迎指正!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/287641.html
標籤:其他
