今天想要來介紹Swift 圖表的第三方套件,未來也有機會可以使用到作為資料的呈現
使用cocoapods來安裝
pod 'Charts'
在專案中要import套件
import Charts
使用Xib建立該View,這些View都是繼承自UIView
記得要使用某種特定類型的Charts要先看看文件,你要使用哪種charts,customClass使用該Class
舉個例子我要使用折線圖,我的customClass就要使用lineChartView
開始建構我的線條圖
class LineChartViewController: UIViewController {
@IBOutlet weak var lineChartView: LineChartView!
// 我的線圖的每筆資料
let item2 = [
BarChartDataEntry(x: 14, y: 8),
BarChartDataEntry(x: 15, y: 19),
BarChartDataEntry(x: 16, y: 12),
BarChartDataEntry(x: 17, y: 22)
]
override func viewDidLoad() {
super.viewDidLoad()
let lineChartDataSet2 = LineChartDataSet(entries: item2, label: "油價")
// 是否開啟圓圈
lineChartDataSet2.drawCirclesEnabled = false
// 設定線條間的樣式
lineChartDataSet2.mode = .cubicBezier
// 設定顏色
lineChartDataSet2.colors = [.green]
// 是否開啟十字highlight線
lineChartDataSet2.highlightEnabled = false
// 填滿下方
lineChartDataSet2.drawFilledEnabled = true
let gradientColors = [UIColor.green.cgColor, UIColor.clear.cgColor] // Colors of the gradient
let colorLocations:[CGFloat] = [1.0, 0.0] // Positioning of the gradient
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors as CFArray, locations: colorLocations) // Gradient Object
let gradienFill = LinearGradientFill(gradient: gradient!, angle: 120.0) // Set the Gradient
let colorFill = ColorFill.init(cgColor: UIColor.green.cgColor)
// 開啟漸層
lineChartDataSet2.fill = gradienFill
let lineDatasets = [lineChartDataSet2]
let lineChartData = LineChartData(dataSets: lineDatasets)
// 客製化下方的型別
let formatter = NumberFormatter()
formatter.positiveSuffix = "年"
lineChartView.xAxis.valueFormatter = DefaultAxisValueFormatter(formatter: formatter)
// Xaxis的位置
lineChartView.xAxis.labelPosition = .bottom
// Xaxis後方的Grid間隔
lineChartView.xAxis.granularityEnabled = true
lineChartView.xAxis.granularity = 1.0
// 餵進去Data
lineChartView.data = lineChartData
// Do any additional setup after loading the view.
}
}
成果展示