一、项目需要实现图表(折线图)的功能,由于IOS并没有原生的控件可以开发图表,经在网络上搜索决定使用PNChart第三方库实现折线图的功能,PNChart还可以创建柱状图、饼图、圆形进度条等图表视图,我就不再一一的举例实现相关的视图。
(1)创建一个折线图;
//折线图 self.lineChart = [[PNLineChart alloc] initWithFrame:CGRectMake(0, 30, [UIScreen mainScreen].bounds.size.width, 200)]; self.lineChart.legendStyle = PNLegendItemStyleStacked; self.lineChart.delegate = self; self.lineChart.showCoordinateAxis = YES; //显示坐标系 self.lineChart.showGenYLabels = YES; self.lineChart.showLabel = YES; self.lineChart.thousandsSeparator = YES; [self.lineChart setXLabels:@[@"1月",@"2月",@"3月",@"4月",@"5月",@"6月",@"7月",@"8月",@"9月",@"10月",@"11月",@"12月"]]; NSArray *data01Array = @[@60.1, @160.1, @126.4, @262.2, @186.2, @60.1, @160.1, @126.4, @262.2, @186.2, @60.1, @160.1]; PNLineChartData *data01 = [PNLineChartData new]; //chart数据 data01.dataTitle = @"Alpha"; data01.color = PNFreshGreen; //折线的颜色 data01.itemCount = self.lineChart.xLabels.count; //x轴坐标item数 data01.inflexionPointStyle = PNLineChartPointStyleCircle; //数值点的样式 data01.getData = ^(NSUInteger index) { CGFloat yValue = [data01Array[index] floatValue]; return [PNLineChartDataItem dataItemWithY:yValue]; }; self.lineChart.chartData = @[data01]; [self.lineChart strokeChart]; //画折线,带动画 //PNChartDelegate委托的实现 - (void)userClickedOnLinePoint:(CGPoint)point lineIndex:(NSInteger)lineIndex { NSLog(@"Click on line %f, %f, line index is %d",point.x, point.y, (int)lineIndex); } - (void)userClickedOnLineKeyPoint:(CGPoint)point lineIndex:(NSInteger)lineIndex pointIndex:(NSInteger)pointIndex { NSLog(@"Click Key on line %f, %f line index is %d and point index is %d",point.x, point.y,(int)lineIndex, (int)pointIndex); //在这个位置弹出逻辑 }
(2)更新折线图的数据;
你可以创建一个更新的按钮或者是一些选项卡来更新lineChart的内容;
//更新折线的数据 - (void)updateView { NSArray *data01Array = @[@80.1, @180.1, @126.4, @292.2, @186.2, @80.1, @160.1, @126.4, @262.2, @186.2, @80.1, @160.1]; PNLineChartData *data01 = [PNLineChartData new]; data01.dataTitle = @"Alpha"; data01.color = PNFreshGreen; data01.itemCount = self.lineChart.xLabels.count; data01.inflexionPointStyle = PNLineChartPointStyleCircle; data01.getData = ^(NSUInteger index) { CGFloat yValue = [data01Array[index] floatValue]; return [PNLineChartDataItem dataItemWithY:yValue]; }; [self.lineChart updateChartData:@[data01]]; [self.lineChart strokeChart]; }
折线图效果: