@@ -31,7 +31,9 @@ - (id)initWithCoder:(NSCoder *)decoder
31
31
- (void )loadDefaults
32
32
{
33
33
self.opaque = NO ;
34
-
34
+
35
+ _xLabels = nil ;
36
+
35
37
_autoMax = YES ;
36
38
37
39
_barColor = [UIColor colorWithRed: 106.0 /255 green: 175.0 /255 blue: 232.0 /255 alpha: 1 ];
@@ -51,10 +53,28 @@ - (void)drawRect:(CGRect)rect
51
53
NSInteger numberOfBars = self.data .count ;
52
54
CGFloat barWidth = (CGRectGetWidth (rect) - self.barSpacing * (numberOfBars - 1 )) / numberOfBars;
53
55
CGFloat barWidthRounded = ceil (barWidth);
54
-
56
+
57
+ if (self.xLabels ) {
58
+ CGFloat fontSize = floor (barWidth);
59
+ CGFloat labelsTopMargin = ceil (fontSize * 0.33 );
60
+ barMaxHeight -= (fontSize + labelsTopMargin);
61
+
62
+ [self .xLabels enumerateObjectsUsingBlock: ^(NSString *label, NSUInteger idx, BOOL *stop) {
63
+ NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc ]init] ;
64
+ paragraphStyle.alignment = NSTextAlignmentCenter;
65
+
66
+ [label drawInRect: CGRectMake (idx * (barWidth + self .barSpacing), barMaxHeight + labelsTopMargin, barWidth, barWidth)
67
+ withAttributes: @{
68
+ NSFontAttributeName :[UIFont fontWithName: @" HelveticaNeue" size: fontSize],
69
+ NSForegroundColorAttributeName :[UIColor colorWithWhite: 0.56 alpha: 1 ],
70
+ NSParagraphStyleAttributeName :paragraphStyle,
71
+ }];
72
+ }];
73
+ }
74
+
55
75
for (NSInteger i = 0 ; i < numberOfBars; i += 1 )
56
76
{
57
- CGFloat barHeight = barMaxHeight * [self .data[i] floatValue ] / max;
77
+ CGFloat barHeight = (max == 0 ? 0 : barMaxHeight * [self .data[i] floatValue ] / max) ;
58
78
if (barHeight > barMaxHeight) {
59
79
barHeight = barMaxHeight;
60
80
}
@@ -83,6 +103,12 @@ - (void)setData:(NSArray *)data
83
103
[self setNeedsDisplay ];
84
104
}
85
105
106
+ - (void )setXLabels : (NSArray *)xLabels
107
+ {
108
+ _xLabels = xLabels;
109
+ [self setNeedsDisplay ];
110
+ }
111
+
86
112
- (void )setMax : (CGFloat)max
87
113
{
88
114
_max = max;
0 commit comments