1、系統注冊cell的兩種方式
【1】、在viewDidLoad 方法里面注冊
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
【2】、系統推薦用這個方法,這個方法在某些情況下更加能避免循環復用(像你在cell里面修改某個控件內容的時候)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//如果隊列中沒有該類型cell,則會返回nil,這個時候就需要自己創建一個cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
}
2、自定制cell
【1】,不使用xib的情況下
<1>、[self.tableView registerClass:[xxxxCell class] forCellReuseIdentifier:@"cell"];
xxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
<2>、
xxxxCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell==nil) {
cell=[[xxxxCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
【2】在使用xib的情況下
<1>、
[tableView registerNib:[UINib nibWithNibName:@"xxxxViewCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
xxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
<2>、
xxxxCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell=[[[NSBundle mainBundle]loadNibNamed:@“xxxxCell" owner:self options:nil]lastObject];
}
在使用自定制cell的時候,如果不使用xib,那么要調一下方法
//創建cell的時候就會默認調用這個方法
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
//在這里創建你自己的子控件
self.iconView = [[UIImageView alloc] init];
self.titleLabel = [[UILabel alloc] init];
self.detailLabel = [[UILabel alloc] init];
self.priceLabel = [[UILabel alloc] init];
self.titleLabel.backgroundColor = [UIColor redColor];
self.detailLabel.backgroundColor = [UIColor greenColor];
self.priceLabel.backgroundColor = [UIColor cyanColor];
//添加子控件
[self.contentView addSubview:self.iconView];
[self.contentView addSubview:self.titleLabel];
[self.contentView addSubview:self.detailLabel];
[self.contentView addSubview:self.priceLabel];
}
return self;
}
//即將布局子控件就會調用這個方法,我們在這里完成cell里面子控件的相對布局
- (void)layoutSubviews
{
//重寫這個方法,一定要記得手動調用父類方法。
[super layoutSubviews];
}
在使用xib的時候直接拉控件就可以啦
當一個文件中有多個tableView的時候每一個cell注冊一定要使用不同的cellID,不然會報錯,還有如果用xib在cell上拉控件的時候要注意不要不小心把控件拉到cell的外邊,不然也會報錯。報錯信息別為
instantiated view controller with identifier "UIViewController-BYZ-38-t0r" from storyboard "Main", but didn't get a UITableView.'