我们在做一些类似于九宫格的排列时,首先会创建 scrollView,然后再自定制一个 view类(继承自 UIView),
比如: 里面我们给两个属性
@property(strong,nonatomic)UIImageView *headImage;//存放图片
@property(strong,nonatomic)UILabel *lb;//存放标题等文字信息
然后在它的.m 方法里对 initFram 初始化方法进行重写,
代码:
-(id)initWithFrame:(CGRect)frame
{
self= [super initWithFrame:frame];
if (self) {
//将图片添加到自定制View
self.headImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height-30)];
self.headImage.backgroundColor=[UIColor orangeColor];
[self addSubview:self.headImage];
self.lb=[[UILabel alloc]initWithFrame:CGRectMake(0, self.bounds.size.height-25, self.bounds.size.width, 20)];
self.lb.backgroundColor=[UIColor blueColor];
[self addSubview:self.lb];
}
return self;
}
每次创建自定制的 View对象 时都会调用初始化方法来初始化这个对象 这个做的好处是 在其他类创建 view 对他进行 initFram 初始化时会自动创建 view 中的成员,因为九宫格这种布局大致样式都是一样的,这样就不用再对view 内的对象一 一设置.
顺便提一下 九宫格的布局设置
int i=0; //控制排列的间距 以及 scrollView 的 contentsize 属性
for (Students *stu in array) {
CustomView *view=[[CustomView alloc]initWithFrame:CGRectMake(i%3*100+45, i/3*150, 95, 145)];
view.lb.text=stu.name;
view.headImage.image=[UIImage imageWithData:stu.headImage];
[_scrollV addSubview:view];
i++;
}
//设置滚动视图的contentsize
_scrollV.contentSize=CGSizeMake([UIScreen mainScreen].bounds.size.width, (i+2)/3*150);