barChartViewDemo.gif
說明:
公司的項目需要用到一個簡單的柱狀圖View
,實(shí)現(xiàn)以下功能:
- 實(shí)時更新顯示
n
列數(shù)據(jù)(n由初始化時確定)
- 將用戶選中某列數(shù)據(jù)的操作通知給后臺
- 可定制柱形圖 僅顯示正數(shù)據(jù)与殃,僅顯示負(fù)數(shù)據(jù)担巩,顯示正負(fù)數(shù)據(jù)
- Y 軸刻度可根據(jù)所顯示的數(shù)據(jù)大小自動適配
網(wǎng)上有很多開源的柱形圖框架,功能豐富樣子炫酷酝陈,但大多過于龐大帜矾。公司這個完整的App
總共才5M
多翼虫,不允許使用一個4M
的柱狀圖的。
為避免牛刀殺雞屡萤,我自己寫了這么個BarChartView
珍剑,剛好實(shí)現(xiàn)了公司項目的需求。這也是我學(xué)OC以來所寫的“處女View”
灭衷,寫的不好次慢,功能也極其有限,還請見諒翔曲。
使用方法:
-
拷貝以下文件到你的項目中:
BarChartView.h BarChartView.m
-
導(dǎo)入頭文件并使用 initWithFrame: 初始化 view :
#import "BarChartView.h" //...... //...... @property(strong,nonatomic)BarChartView *barChartView; //...... //...... _barChartView = [[BarChartView alloc] initWithFrame:CGRectMake(x,y,width,height)];
-
通過 點(diǎn)操作 或 設(shè)值方法 來自定義 view 的一些屬性迫像,可定義的屬性如下:
self.backgroundColor; //背景色(默認(rèn):yellow) @property(nonatomic,assign)ChartType chartType; //1.Normal 2.OnlyPlus 3.OnlyMinus(默認(rèn):Normal) @property(nonatomic,strong)UIColor *columnColor; //柱子顏色(默認(rèn):gray) @property(nonatomic,strong)UIColor *columnValueColor; //柱子上/下的數(shù)值顏色(默認(rèn):black) @property(nonatomic,strong)UIColor *columnSelectedColor; //柱子在被選中狀態(tài)的顏色(默認(rèn):green) @property(nonatomic,strong)UIColor *shadowButtonColor; //柱子被選中時陰影的顏色(默認(rèn):gray) @property(nonatomic,strong)UIColor *lineColor; //y刻度線的顏色(默認(rèn):gray) @property(nonatomic,strong)UIColor *xLineColor; //x軸的顏色(默認(rèn):black) @property(nonatomic,strong)UIColor *yUnitColor; //單位Label的顏色(默認(rèn):gray) @property(nonatomic,strong)UIColor *yCoordinateColor; //y刻度值的顏色(默認(rèn):gray) @property(nonatomic,strong)NSString *yUnit; //單位(默認(rèn):@“單位”) @property(nonatomic,assign)NSInteger lineNumber; //y刻度線的數(shù)量,請設(shè)置為>=3的奇數(shù)以保證x軸在中間(默認(rèn):7) @property(nonatomic,assign)NSInteger columnNumber; //柱子數(shù)量(默認(rèn):3) @property(nonatomic,strong)NSArray *yCoordinateFixed; //y軸刻度 //當(dāng)且僅當(dāng) columnNumber==1 時需要自行設(shè)置, //為固定的長7的數(shù)組瞳遍,依次表示從小到大的七個y刻度值闻妓,最大值即為柱狀圖量程 //如默認(rèn)為:@[@"-60",@"-40",@"-20",@"0",@"20",@"40",@"60"]; @property(nonatomic,assign)NSInteger accuracy; //數(shù)據(jù)精度,小數(shù)點(diǎn)后幾位(默認(rèn):1掠械,表示1位小數(shù)) @property(nonatomic,assign)CGFloat animateDuration; //數(shù)據(jù)改變時柱子的動畫時間(默認(rèn):0.7) @property(nonatomic,assign)CGFloat columnWidthScale; //柱子相對寬度比由缆,0~1(默認(rèn):0.6) @property(nonatomic,assign,readonly)NSInteger selectedColumnIndex; //當(dāng)前被選中柱子的下標(biāo),為只讀屬性
-
可選擇實(shí)現(xiàn)
BarChartViewDelegate
@protocol BarChartViewDelegate <NSObject> -(void)clickedColumnAtIndex:(NSInteger)index;//當(dāng)用戶點(diǎn)擊某柱數(shù)據(jù)時,將回調(diào)該方法 @end
-
調(diào)用方法將要展示的數(shù)據(jù)傳給
view
進(jìn)行顯示-(void)sendDataValue:(CGFloat)dataValue atIndex:(NSInteger)index; //index表示柱子下標(biāo)猾蒂,自左向右依次為:0均唉,1,2... //要清楚某列數(shù)據(jù)肚菠,只需調(diào)用:sendDataValue:0 atIndex:index舔箭;
有興趣的朋友們可自行下載源碼,歡迎大家提出寶貴意見蚊逢。