iOS 使用 Charts 库实现分时K线及指标

Posted 追夢秋陽

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 使用 Charts 库实现分时K线及指标相关的知识,希望对你有一定的参考价值。

       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)
    

由于篇幅有限指标计算以及源码和其他问题可留言咨询获取,相应参数设置见文中备注描述。

本文结束,欢迎指正!

以上是关于iOS 使用 Charts 库实现分时K线及指标的主要内容,如果未能解决你的问题,请参考以下文章

iOS Swift Charts 的使用(一):折线图的实现

手把手教你画AndroidK线分时图及指标

iOS图表库Charts使用(不常见但很实用的属性)

iOS 使用Charts框架 折线,柱状,K线,饼状,雷达全攻略

iOS上股票类应用中的K线图效果怎么实现

如何在 Swift 语言下使用 iOS Charts API 制作漂亮图表