fayeah / blogs

方法论、问题驱动、总结
6 stars 0 forks source link

【iOS】使用Carthage添加Chart依赖 #4

Open fayeah opened 4 years ago

fayeah commented 4 years ago

最近没上项目,在跟着公司学习native的开发,4周实现一个POC。那刚刚做的是要显示一个柱状图,google了一下,使用最多的是Charts,毫无疑问就用这个library了。也是遇到一些坑,这里有个总结。

Prerequisite: xCode 11.3, Swift5, Carthage 0.34.0

添加Charts依赖

这里我们使用的包管理工具是Carthage,还有一个使用比较多的是Cocopods。因为Cocopods出现的比较早,到现在也是各种各样的feature,很重。那Carthage相对比较新,也比较轻量级,口碑也不错,所以我们选定的Carthage做我们的包管理工具。 Step 1: 在Cartfile里面添加 github "danielgindi/Charts" ~> 3.4.0

Step 2: 在terminal里面run carthage update --platform iOS,这里注意一下,如果不加platform参数,那么默认会为所有的platform进行安装,包括iOS,MacOS, tvOS, watchOS, etc.

Step 3: 进入到Carthage/Build/iOS目录,将Charts.framework拖拽到xCode中。 image

Step 4: 到xCode的Build Phases里面找到Carthage在Input Files里面添加$(SRCROOT)/Carthage/Build/iOS/Charts.framework,Output Files里面添加$(DERIVED_FILE_DIR)/Carthage/Build/iOS/Charts.framework。这里我们的假设是已经添加好Carthage了。 image

至此,Chart依赖就添加完成了。

画一个柱状图

涉及到2个文件,一个是storyboard,另外一个是view controller。 Step 1: 在storyboard中添加一个UIView,并在custom class中设置module为Charts,这个很重要。看需要设置,我这里需要的是柱状图,所以class填的是BarChartViewimage

Step 2: 将该UIView connect到view controller里面,IBOutlet的设置。(按住control拖拽该view到view controller里面)

Step 3: 在view controller里面设置图表样式:

@IBOutlet weak var barChartView: BarChartView!
    let timeslots = ["9:00", "11:00", "13:00", "15:00", "18:00"]
    let steps = [6, 8, 26, 30, 8]

    override func viewDidLoad() {
        super.viewDidLoad()
        customizeChart(dataPoints: timeslots, values: steps.map{ Double($0) })
    }

    func customizeChart(dataPoints: [String], values: [Double]) {
        var dataEntries: [BarChartDataEntry] = []
        barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
        barChartView.rightAxis.enabled = false
        barChartView.leftAxis.enabled = false
        barChartView.xAxis.drawGridLinesEnabled = false
        barChartView.leftAxis.drawLabelsEnabled = false
        barChartView.legend.enabled = false
        for i in 0..<dataPoints.count {
          let dataEntry = BarChartDataEntry(x: Double(i), y: Double(values[i]))
          dataEntries.append(dataEntry)
        }
        let chartDataSet = BarChartDataSet(entries: dataEntries, label: "Bar Chart View")
        let chartData = BarChartData(dataSet: chartDataSet)
        barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: timeslots)
        barChartView.xAxis.granularity = 1
        barChartView.data = chartData
    }

Reference(英文版的carthage添加Almofire,一个http的依赖): https://medium.com/@kevinle/step-by-step-guide-on-using-carthage-dependency-manager-a29c15f9a1ac