//取文件内容
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"faceMap_ch" ofType:@"plist"];
NSArray *buttons = [[NSArray alloc]initWithContentsOfFile:filePath];
//总共有多少页
int line = 5;
int row = 2;
int sum = line * row;
float total = buttons.count;
//ceilf((float)x)返回大于X的最小整数
//(1)等于整数 ceilf(2.0) = 2.0
//(2)大于整数 ceilf(1.2) = 2.0 ceilf(1.8) = 2.0
//当正好是整数屏时,返回整数,当比整数屏还要多一些的时候,返回整数屏+1,因此用到一个ceil函数
int pages = (int)ceilf(total/sum);
float scrollViewheight = self.frame.size.height;
_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, scrollViewWidth, scrollViewheight)];
_scrollView.backgroundColor = [UIColor yellowColor];
_scrollView.pagingEnabled = YES;
_scrollView.contentSize = CGSizeMake(pages*scrollViewWidth, scrollViewheight);
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.delegate = self;
[self addSubview:_scrollView];
float height = self.scrollView.frame.size.height;
float padding = 10;
float btnSize = (320.0 - (line+1)*padding)/line; //根据列计算按钮的大小
float margin = (height - row*btnSize)/(row+1); //计算行间距
for (int i = 1; i<=total; i++) {
NSDictionary *dic = [buttons objectAtIndex:i-1];
NSString *class = [dic objectForKey:@"class"];
NSString *title = [dic objectForKey:@"title"];
NSString *imageName = [dic objectForKey:@"image"];
MButton *btn = [MButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
btn.backImage = [UIImage imageNamed:imageName];
btn.buttonClass = class;
btn.title = title;
int page = (i-1)/sum*320; //第几屏
int hIndex = ((i-1)%sum)%line; //横向x坐标
float x = page + padding + (btnSize +padding)*hIndex; //padding横向间距
int vIndex = ((i-1)%sum)/line; //纵向x坐标
float y = margin + (btnSize +margin)*vIndex; //margin纵向间距
btn.frame = CGRectMake(x, y, btnSize, btnSize);
[_scrollView addSubview:btn];
}
//例子说明
for (int index = 1; index <= 10; index++) {
int row = 2;
int line = 3;
int sum = row * line;
int a = (((index-1)%sum)%line);
int b = ((index-1)%sum)/line;
NSLog(@" x = %d y = %d",a,b);
}
结果:
2013-11-26 14:54:57.610 test[4266:a0b] x = 0 y = 0
2013-11-26 14:54:57.611 test[4266:a0b] x = 1 y = 0
2013-11-26 14:54:57.611 test[4266:a0b] x = 2 y = 0
2013-11-26 14:54:57.611 test[4266:a0b] x = 0 y = 1
2013-11-26 14:54:57.612 test[4266:a0b] x = 1 y = 1
2013-11-26 14:54:57.612 test[4266:a0b] x = 2 y = 1
2013-11-26 14:54:57.612 test[4266:a0b] x = 0 y = 0
2013-11-26 14:54:57.612 test[4266:a0b] x = 1 y = 0
2013-11-26 14:54:57.616 test[4266:a0b] x = 2 y = 0
2013-11-26 14:54:57.616 test[4266:a0b] x = 0 y = 1
demo:http://download.csdn.net/detail/xiekunmiao/6613689