我们在开发中多多少少会遇到九宫格要求布局UI 如下图
直接上代码
//每个Item宽高
CGFloat W = 80;
CGFloat H = 100;
//每行列数
NSInteger rank = 4;
//每列间距
CGFloat rankMargin = (self.view.frame.size.width - rank * W) / (rank - 1);
//每行间距
CGFloat rowMargin = 20;
//Item索引 ->根据需求改变索引
NSUInteger index = 9;
for (int i = 0 ; i< index; i++) {
//Item X轴
CGFloat X = (i % rank) * (W + rankMargin);
//Item Y轴
NSUInteger Y = (i / rank) * (H +rowMargin);
//Item top
CGFloat top = 50;
UIView *speedView = [[UIView alloc] init];
speedView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"taozi"]];
speedView.frame = CGRectMake(X, Y+top, W, H);
[self.view addSubview:speedView];
}
只需要按照需求更改一下即可