关于tableview的重用机制,一般有两种解决方案
第一种:就是把你要加载到cell上的subview,?*****f(cell==nil){ }这个判断里面加入,然后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];
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;
}
第二种方法就是,每次加载的时候,把原来的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;
}
|