一開始使用tableview的時候,碰到最多的問題就是復(fù)用問題了,下面是我對有關(guān)于復(fù)用問題的總結(jié)。
首先我們創(chuàng)建一個基本的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 的復(fù)用機制,其實就是將一個cell重復(fù)多次使用,這個內(nèi)部的使用順序是沒有規(guī)則的,比如你創(chuàng)建了多個cell,每個cell 都會進入這個方法中,但是實際創(chuàng)建的只有一個cell,其余都為重復(fù)使用的,如果你想在這上面加載一個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;
}
上述這種情況就會產(chǎn)生復(fù)用問題,不能在這個方法里面寫 alloc init,因為你的cell當(dāng)從復(fù)用池調(diào)出時,cell本身就可能已經(jīng)加載過一次,還存在上一個view,不做出判斷,那么又會加載一個view覆蓋上去,就會出現(xiàn)復(fù)用的問題了。
可以在cell 的創(chuàng)建方法上創(chuàng)建這個view,或者判斷cell 是否已經(jīng)創(chuàng)建過了。
#import "addShopDetailTableViewCell.h"
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.view =[ [uiview alloc]init];
}
return self;
}
設(shè)置他的屬性
-(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 的時候,如果界面中出現(xiàn)tabbar,而不給self.tableView設(shè)置frame,在ios10.0以下的系統(tǒng)將無法識別高度,會導(dǎo)致tableviewHeadView 與cell重疊,10.0以上不設(shè)置也可以,這個bug有點隱秘,自己也是找了好久才發(fā)現(xiàn)。
總之,在使用cell復(fù)用時,不要在這個方法里面進行alloc init 的使用,希望對剛剛接觸的朋友們有一點幫助。