- 1.效果图:
1.png
- 2.计算思路:
2.png
- 3.代码:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
[self setupButton];
}
- (void)setupButton{
int totalloc = 4;//一行的列数
CGFloat appViewW = 80; //按钮的宽度
CGFloat appViewH = 80; //按钮的高度
//间隙= (整个屏幕的宽度-总列数*每个的宽度)/(总列数+1)即间隙
CGFloat margin = (self.view.frame.size.width-appViewW*totalloc)/(totalloc+1);
int count = 4; //总按钮的数量
for(int i = 0 ; i<count;i++){
int row = i/totalloc;//行号
int loc = i%totalloc;//列号
CGFloat appViewX = margin + (margin + appViewW) * loc; //x值由列号决定
CGFloat appViewY = margin + (margin + appViewW) * row; //x值由行号决定
UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(appViewX, appViewY, appViewW, appViewH);
btn.backgroundColor = [UIColor redColor];
[self.view addSubview:btn];
}
}