原理:给自定义的View类两个数组类型的参数,一个存年份,一个存收入,并且传入参数添加手势。在外面调用的时候只需要传入两个数组即可。
核心算法:以数组形式传入的年份依次赋给UILabel,以数组形式传入的收入来计算柱条的高度,这里关键是需要计算柱条的起点纵坐标即可
y(起点纵坐标)=frame.size.height-50 - num*(frame.size.height-50)/2000.0;
等于最大允许高度 减去 最大允许高度 *(数组数据值/数据范围最大值)
Height-Height *(array[i]/定值A) 注意:如果数据范围在0-2000,那么这里的定值A就是2000;
点击手势:添加点击手势使得点击柱条的时候使用UIView动画控制的 的alpha值变化显示一个UILabel来展示数据(动画很简单暂略)
使用方法如下:
#import "MyView.h"
MyView *myVIew = [[MyView alloc]initWithFrame:CGRectMake(50, 100, 300, 400) yearArr:@[@"2001",@"2002",@"2003",@"2004"] numberArr:@[@"1000",@"500",@"1500",@"2000"] target:self action:@selector(clickpic:)];
[self.view addSubview:myVIew];
下面具体说明如何封装柱状图:
a.方法声明
@interface MyView : UIView
- (instancetype)initWithFrame:(CGRect)frame yearArr:(NSArray *)yearArr numberArr:(NSArray *)numberArr target:(id)target action:(SEL)action;
@end
b.方法实现
@implementation MyView
- (instancetype)initWithFrame:(CGRect)frame yearArr:(NSArray *)yearArr numberArr:(NSArray *)numberArr target:(id)target action:(SEL)action
{
self = [super initWithFrame:frame];
if (self) {//此处计算的是高度
self.backgroundColor = [UIColor yellowColor];
self.userInteractionEnabled = YES;
labY.backgroundColor = [UIColor blackColor];
[self addSubview:labY];
float a = yearArr.count;
NSInteger b = frame.size.width/(a);
for (int i=0; i< a; i++) {
//每年数据
NSString *number = numberArr[i];
float num = [number floatValue];
//年份
NSString *year = yearArr[i];
UILabel *showlab = [[UILabel alloc]initWithFrame:CGRectMake(i*b,frame.size.height-50 - num*(frame.size.height-50)/2000.0, b-1, num*(frame.size.height-50)/2000.0)];
UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
//打开交互,否则不会响应
showlab.userInteractionEnabled = YES;
//添加手势
[showlab addGestureRecognizer:imageTap];
//添加边框
showlab.layer.borderWidth = 1;
showlab.layer.borderColor = [[UIColor blackColor]CGColor];
//使用随机色
showlab.backgroundColor =
[self randomColor];
showlab.tag = 100+i;
[self addSubview:showlab];
UILabel *yearLab = [[UILabel alloc]initWithFrame:CGRectMake(i*b, frame.size.height-50, b-1, 48)];
yearLab.text = year;
yearLab.textAlignment = 1;
//使得年份和每年数据颜色一致
yearLab.textColor = showlab.backgroundColor;
[self addSubview:yearLab];
}
}
return self;
}
//自定义的随机数颜色方法
- (UIColor*)randomColor
{
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}