關(guān)于tableview的重用機(jī)制,一般有兩種解決方案
第一種:就是把你要加載到cell上的subview,?*****f(cell==nil){ }這個(gè)判斷里面加入,然后subview上面要加入的值在判語(yǔ)句外面加入,舉個(gè)例子:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * cellID=@"cellID";
UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:cellID];
UILabel * label1=nil;
UILabel * label2=nil;
if(cell==nil){
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID]autorelease];
label1=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 30)];
[cell addSubview:label1];
label2=[[UILabel alloc]initWithFrame:CGRectMake(10, 50, 100, 30)];
[cell addSubview:label2];
}
label1.text=[NSString stringWithFormat:@"number is %d",indexPath.row];
label2.text=[NSString stringWithFormat:@"we are the same %d",indexPath.row];
return cell;
}
第二種方法就是,每次加載的時(shí)候,把原來(lái)的subview都刪除了,重新加載。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * cellID=@"cellID";
UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:cellID];
UILabel * label1=nil;
UILabel * label2=nil;
if(cell==nil){
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID]autorelease];
}
for(UIView * view in cell.subviews){
if([view isKindOfClass:[UILabel class]])
{
[view removeFromSuperview];
}
}
label1=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 30)];
label1.text=[NSString stringWithFormat:@"number is %d",indexPath.row];
[cell addSubview:label1];
label2=[[UILabel alloc]initWithFrame:CGRectMake(10, 50, 100, 30)];
label2.text=[NSString stringWithFormat:@"we are the same %d",indexPath.row];
[cell addSubview:label2];
return cell;
}
|