UITableViewCell的循環(huán)利用方式

方式一

//被static修飾的局部變量:只會初始化一次,在整個程序運行過程中,只有一份內(nèi)存
static NSString *ID = @"cell";
/**
 * 什么時候調(diào)用:每當(dāng)有一個cell進(jìn)入視野范圍內(nèi)就會調(diào)用
 */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   //1. 設(shè)置重用標(biāo)示
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    //2.如果cell為nil(緩存池找不到對應(yīng)的cell)
    if(cell==nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableVIewCellStyleDefault reuseIdentifier:ID];
    }
    //3.顯示數(shù)據(jù)
    cell.textLabel.text = [NSString stringWithFormat:@"testDate - %zd",indexPath.row];
    return cell;
}

方式二

  • 定義全局變量
//定義重用標(biāo)示符
NSString *ID = @"cell";
  • 注冊某個標(biāo)識對應(yīng)cell類型
//在這個方法中注冊cell
-(void)viewDidLoad
{
    [super viewDidLoad];
    //注冊某個標(biāo)識對應(yīng)的cell類型
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}
  • 數(shù)據(jù)源方法中返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      //1.去緩存池中查找cell
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
      //2.顯示數(shù)據(jù)
      cell.textLabel.text = [NSString stringWithFormat:@"testdata - %zd", indexPath.row];
      return cell;
}

方式三

  • 在storyboard中設(shè)置UITableView的Dynamic Prototypes Cell
Snip20150602_152.png
  • 設(shè)置cell的重用標(biāo)識
Snip20150602_153.png
  • 在代碼中利用重用標(biāo)識獲取cell

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     // 1. 重用標(biāo)識,被static修飾的局部變量:只會初始化一次,在整個程序運行過程中,只有一份內(nèi)存
    static NSString *ID = @"cell";
    // 2. 先根據(jù)cell的標(biāo)識去緩存池中查找可循環(huán)利用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 3. 覆蓋數(shù)據(jù)
    cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd", indexPath.row];
    return cell;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容