UITableViewCell的创建方式

2016-12-06  本文已影响0人  iOS小白_昊然

第一种

// 纯代码注册:
//  系统的UITableViewCell
[self.tableView registerClass:[UITableViewCell class]  forCellReuseIdentifier:@"cell”];
// [self.tableView registerClass:UITableViewCell.class  forCellReuseIdentifier:@"cell”]; 
 //  自定义的UITableViewCell
[self.tableView registerClass:[OrderBtnTableViewCell class] forCellReuseIdentifier:@"cellId"];
// 设置代理
 self.tableView.delegate = self;
// 设置数据源
 self.tableView.datasource = self;```

- 第二步: 在```- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath``` 方法中
```objc
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
                                                           
 cell.textLabel.text = self.titles[indexPath.row];
    
 return cell;

第二种

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法中

    static NSString *identifier = @"identifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.textLabel.text = self.titles[indexPath.row];

    return cell;

注意

  1. 先注册
  2. 再设置代理
  3. 当cell为nil,需要创建新的cell的时候,使用的是initWithStyle:reuseIdentifier:方法,而不是init方法,这样做是因为创建新的cell的时候需要绑定一个identifier,这样在重用的时候才能找到可重用的相同类型。
  4. 一般在if(!cell)中,也就是在新创建cell的时候,将一些只需要初始化一次的属性进行初始化,而不是在这个括号的外面。同样,如果不同的cell需要设置不同属性或数据,那么需要在括号外执行,因为括号外面每次cell出现都会执行到,这样可以保证不用的cell对应不同的属性或数据。

重用机制原理

上一篇 下一篇

猜你喜欢

热点阅读