1 創(chuàng)建UITableView設置相關屬性時注冊
// xib cell注冊
[tableView registerNib:[UINib nibWithNibName:NSStringFromClass([UITableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
// 純代碼 cell注冊
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
如果先注冊了鹉勒,那么tableView調(diào)用數(shù)據(jù)源方法tableView:cellForRowAtIndexPath:
時就不用再注冊脱盲,直接可以使用dequeueReusableCellWithIdentifier:forIndexPath:
就會重用狱从,其實我實驗過用dequeueReusableCellWithIdentifier
也是會重用的翠胰,但還是建議用前者,因為后者一般配合在tableView:cellForRowAtIndexPath:
方法里面注冊使用拍鲤。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
return cell;
}
2 在數(shù)據(jù)源方法里面注冊(適用于未能提前知道Identifier剩檀,如從接口獲取的Identifier)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
// xib的cell注冊
if(cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([UITableViewCell class]) owner:self options:nil] firstObject];
}
// 純代碼的cell注冊
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
}
return cell;
}
3 直接在xib cell里面注冊
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
NSLog(@"地址-----%p 第%ld行",cell, indexPath.row + 1);
return cell;
}