UITableViewCell的注冊和初始化

最近在項目開發(fā)的過程中,發(fā)現(xiàn)和同事就關(guān)于UITableViewCell的初始化存在不同之處,在此整理和對比。

不注冊 Cell (iOS 6.0 之前都用這個方法)

TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"test"];
if (cell == nil) {
    cell = [[TestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"test"];
}
return cell;

必須加上if cell == nil的判斷

注冊nib文件

UITableViewCell的創(chuàng)建時通過xib文件創(chuàng)建的
需要在tableView初始化的時候registerNib

[tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:kCellIdentify]; 

在cellForRowAtIndexPath里就不需要對cell 是否為空進行判斷

CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath]; 

注冊代碼創(chuàng)建文件

UITableViewCell的創(chuàng)建是通過代碼創(chuàng)建的

[tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];

同理在cellForRowAtIndexPath 里如下

CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath]; 

兩種 dequeueReusableCellWithIdentifier 區(qū)別

有 forIndexPath 的方法,需配合 registerClass 或 registerNib使用,并且不需要處理cell為nil的情況

最后編輯于
?著作權(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)容