UITableViewCell的三種循環利用方式

第一種方式:

數據源 dataSource 代理方法:
/**
 *  什么時候調用:每當有一個cell進入視野范圍內就會調用
 */

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 0.重用標識:
    // 之前跟一個同學討論過這個問題,確實如此,被static修飾的局部變量:只會初始化一次,在整個程序運行過程中,只有一份內存!
    static NSString *identifier = @"cell";

    // 1.先根據cell的標識去緩存池中查找可循環利用的cell:
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier];

    // 2.如果cell為nil(緩存池找不到對應的cell):
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: identifier];
    }
    // 3.覆蓋數據
    cell.textLabel.text = [NSString stringWithFormat:@"第%d行", indexPath.row];

    return cell;
}

第二種方式:

第二種方式是 richy 老師在周三提到過的register 注冊方法,之前 龍哥沒用過,感覺一個老師一個方法吧!也挺有意思的感覺這個更直接明了就是告訴你我要注冊啦!我要注冊啦~我要注冊啦...

viewDidLoad
// 定義重用標識(定義全局變量)
NSString * identifier = @"cell";

// 在這個方法中注冊cell
- (void)viewDidLoad {
    [super viewDidLoad];

    // 就是這句話!!!寫在viewDidLoad里!寫出重用標識
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier: identifier];
}
數據源 dataSource 代理方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.去緩存池中查找cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier];

    // 2.覆蓋數據
    cell.textLabel.text = [NSString stringWithFormat:@"第%d行", indexPath.row];

    return cell;
}

第三種方式:

第三種方式是聽 MJ 老師的視頻學到的,這個應該算是最簡單的一種了!把代碼與 storyboard 聯系起來,在storyboard的 tableView里右側邊欄 prototype 處把0改為1,這樣 tableView 上就會自己創建出一個系統的 cell ,然后再選擇最頂部的動態形式的 cell, 然后往下看一下就是 identifier!!! 熟悉的節奏!沒錯!!他就是重用標識!!!...... AV8D 跟我一起搖擺吧~~

例圖:
Snip20161028_1.png

Snip20161028_2.png
// 0.重用標識
// 被static修飾的局部變量:只會初始化一次,在整個程序運行過程中,只有一份內存
static NSString * identifier = @"cell";// (重復的創建銷毀創建銷毀對內存影響不好!!!)--> static是一定要加的!否則不流暢~這細微的差別也只有像我這種產品狗一樣敏銳的眼睛能看到~哈哈哈哈
// 1.先根據cell的標識去緩存池中查找可循環利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier];
// 2.覆蓋數據
cell.textLabel.text = [NSString stringWithFormat:@"第%d行", indexPath.row];
return cell;
"本文僅代表作者個人觀點,如有轉載請聯系作者本人,文中疏漏及不當之處還請批評指正"
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容