-
Notifications
You must be signed in to change notification settings - Fork 1
/
SimpleGridView.m
77 lines (56 loc) · 1.81 KB
/
SimpleGridView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#import "SimpleGridView.h"
#define DEFAULT_MARGIN 10
@implementation SimpleGridView
@synthesize columns;
@synthesize margin;
- (void)dealloc
{
[super dealloc];
}
- (id)initWithFrame:(CGRect)frame columns: (NSInteger)nbColumns {
return [self initWithFrame:frame columns:nbColumns margin:DEFAULT_MARGIN];
}
- (id)initWithFrame:(CGRect)frame columns: (NSInteger)nbColumns margin: (NSInteger)aMargin {
if (nbColumns <= 0)
[NSException raise: NSInvalidArgumentException format: @"columns number argument must be positive"];
if (margin < 0)
[NSException raise: NSInvalidArgumentException format: @"margin argument must be positive or equal to zero"];
if ((self = [super initWithFrame:frame])) {
columns = nbColumns;
margin = aMargin;
}
return self;
}
- (void)addSubview:(UIView *)view {
[super addSubview:view];
[self reloadSubviews];
}
- (void)reloadSubviews {
//initialization
int subviewsNumber = [self.subviews count];
CGFloat widthMax = self.bounds.size.width - margin;
CGFloat heightMax = self.bounds.size.height - margin;
//init cells size
CGFloat cellWidth = (widthMax/columns);
CGFloat cellHeight = heightMax;
CGFloat row = ceilf(((CGFloat)subviewsNumber / (CGFloat)columns));
if (row > 0)
cellHeight = (heightMax / row);
int i=0;
int x=0;
int y=0;
int currentRow=0;
//resize and place subviews
for (UIView *aView in self.subviews) {
//update currentRow
if (i%columns==0 && i>0) {
currentRow++;
}
//update position
y = cellHeight*currentRow;
x = cellWidth*(i%columns);
i++;
[aView setFrame:CGRectMake(x+margin, y+margin, cellWidth-margin, cellHeight-margin)];
}
}
@end