深入解析iOS应用开发中九宫格视图布局的相关计算方法
来看一个简单的例子:
/* *总列数 */ NSUIntegertotalloc=3;
/* *View的宽高 */ CGFloatshopW=80; CGFloatshopH=100;
/* *每个View之间的间隔 */ CGFloatmargin=(self.view.frame.size.width-totalloc*shopW)/(totalloc+1);
/* *View的总个数 */ NSUIntegercount=12;
/* * 根据总个数使用总列数来除和取余获取对应的行和列 */ NSUIntegerloc=count/totalloc; NSUIntegerrow=count%totalloc;
/* *View的X和Y */ CGFloatshopX=margin+(margin+shopW)*row; CGFloatshopY=margin+(margin+shopH)*loc;
/* *创建自定义View,设置背景颜色,添加到界面上去 */ UIView*shopV=[[UIViewalloc]initWithFrame:CGRectMake(shopX,shopY,shopW,shopH)]; shopV.backgroundColor=[UIColorlightGrayColor]; [self.shopViewaddSubview:shopV];
/* * 创建UIImageView用于放置图片,设置frame然后加到自定义的View上面 */ UIImageView*imageV=[[UIImageViewalloc]init]; imageV.frame=CGRectMake(0,0,80,80); [shopVaddSubview:imageV];
/* * 创建UILabel用于放置显示文字,设置frame然后加到自定义的View上面 */ UILabel*l=[[UILabelalloc]init]; l.frame=CGRectMake(0,80,80,20); l.textAlignment=NSTextAlignmentCenter; [shopVaddSubview:l];