tableview遇到的常見的問題

一開始使用tableview的時候,碰到最多的問題就是復用問題了,下面是我對有關于復用問題的總結。

首先我們創建一個基本的tableview:

MainTableView=[[UITableView alloc]initWithFrame:CGRectMake(shopDetailView.frame.origin.x, shopDetailView.frame.origin.y+shopDetailView.frame.size.height+20, shopDetailView.frame.size.width, 0) style:UITableViewStylePlain];

MainTableView.dataSource=self;

MainTableView.delegate=self;

[MainTableView registerClass:[addShopDetailTableViewCell class] forCellReuseIdentifier:@"cell1"];

[sele.view addSubview:MainTableView];

在這里使用一個自定義的cell,一般很多情況都會去使用自定義的cell,可以手寫和XIB類型,在這里以手寫的為例:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

addShopDetailTableViewCell *cell = [shopDetailTableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];

cell.selectionStyle = UITableViewCellSelectionStyleNone;

return cell;

}

tableview 的復用機制,其實就是將一個cell重復多次使用,這個內部的使用順序是沒有規則的,比如你創建了多個cell,每個cell 都會進入這個方法中,但是實際創建的只有一個cell,其余都為重復使用的,如果你想在這上面加載一個view,

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

addShopDetailTableViewCell *cell = [shopDetailTableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];

cell.selectionStyle = UITableViewCellSelectionStyleNone;

UIView * view = [[UIView alloc]initWithFrame:cell.bounds];

[cell addSubview:view];

return cell;

}

上述這種情況就會產生復用問題,不能在這個方法里面寫 alloc init,因為你的cell當從復用池調出時,cell本身就可能已經加載過一次,還存在上一個view,不做出判斷,那么又會加載一個view覆蓋上去,就會出現復用的問題了。

可以在cell 的創建方法上創建這個view,或者判斷cell 是否已經創建過了。

#import "addShopDetailTableViewCell.h"

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

self.view =[ [uiview alloc]init];

}

return self;

}


設置他的屬性

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

addShopDetailTableViewCell *cell = [shopDetailTableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];

cell.selectionStyle = UITableViewCellSelectionStyleNone;

cell.view .frame = cell.bounds;

[cell addSubview:view];

return cell;

}

新增:在使用tableviewController 的時候,如果界面中出現tabbar,而不給self.tableView設置frame,在ios10.0以下的系統將無法識別高度,會導致tableviewHeadView 與cell重疊,10.0以上不設置也可以,這個bug有點隱秘,自己也是找了好久才發現。


總之,在使用cell復用時,不要在這個方法里面進行alloc init 的使用,希望對剛剛接觸的朋友們有一點幫助。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容