手动创建控件时注意的点

在声明控件属性时一般声明为weak,(也可用strong,但要注意避免循环引用)重写get方法


@property (nonatomic, weak) UICollectionView *collectionView;

用懒加载的原理重写get方法,直接在其中实例化。注意不要再set,get属性中运用点语法,不然会造成死循环

- (UICollectionView *)collectionView {

if (_collectionView == nil) {

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

//确定是水平滚动,还是垂直滚动

[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];

UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0) collectionViewLayout:flowLayout];

[self addSubview:collectionView];

collectionView.showsHorizontalScrollIndicator = NO;

collectionView.dataSource = self;

collectionView.delegate = self;

collectionView.pagingEnabled = YES;

[collectionView setBackgroundColor:[UIColor clearColor]];

_collectionView = collectionView;

}

return _collectionView;

}


(有关weak实例化的解释:

UIButton *button = [[UIButton alloc]init];

_btn = button;

[self.view addSubview:_btn];

这里的解释是如果直接赋值的话,那么这个对象一创建出来,由于没有强引用去引用他,就出来就死掉了,所以需要使用一个局部指针(作用于内存活)去指向他,然后再让weak指针指向这个局部指针,最后进行add操作,让controller的view的subviews去强引用这个控件)

要用到该控件时时直接使用[self.view addSubview:self.colletionView];即调用属性get方法。这样可以在懒加载中完成初始化控件的所有有关操作,使代码看起来更明朗 简洁。

同理,重写set方法时

- (void)setModel:(Person *)model {

if (_model != model) {

_model = model;

}

//为nameLabel赋值

self.nameLabel.text = model.name;

//为phoneNumberLabel赋值

self.phoneNumberLabel.text = model.phoneNumber;

}

@end

//在配置cell的方法里,调用setter方法,为cell的控件赋值;

//配置cell  设置cell上显示的内容,同时返回cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

//使用自定义cell

//1.创建静态标示符字符串

static NSString *cellIdentifier = @"CELL";

//2.根据重用标示符去重用队列里找对应类型的cell使用,(获取可重用的cell)

CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

//3.判断是否从重用队列中获取到可重用的cell,如果没有获取到,则需要重新创建相对应类型的cell对象

if (cell == nil) {

cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

}

//让cell上的控件显示数据,为cell赋值

cell.model = [self.personArray objectAtIndex:indexPath.row];//即将网络请求数据赋值给model时直接将cell上的控件显示数据

return cell;

}


以上是自己浏览其他作者博客和自己学习时突然想记录下来的一些点 希望对大家有所帮助

你可能感兴趣的:(手动创建控件时注意的点)