最近项目中要用到UITableView,在网上搜了一遍看大家的用法都差不多,我是通过[cell.contentView addSubview:cellView]来添加我自定义的cellView,但我发现了一个问题,在UITableView滚动过一屏后选中后面的一项时会发现和前面的竟然重叠到一起了,后面通过打印[cell.contentView.subviews count]发现随着滚动条的滚动count不断增大。最后通过以下语句解决问题:
for(UIView *view in cell.contentView.subViews)
{
if([view isKindOfClass:[UIView class]])
{
[view removeFromSuperview];
}
}
问题虽然解决了但在和同事的讨论时发现这个问题可能是用法不当造成的。网上找到的代码一般都是
static NSString *tag = @"cell";
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tag]autorelease];
}
……
然后在后面向cell添加数据,网上都是向cell中自带的textLabel添加数据所以不会出现重叠的现象,而我则是向自定义的cellView添加数据,这样只要有滚动它就向里面添加cellView,所以cellView越加越多。后面通过将界面加载与数据加载解决,具体实现如下:
-(UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *tag = @"cell";//由于用了两种界面模式所以两个tag
static NSString *tag1 = @"cell1";
UITableViewCell * cell;
CGRect cellFram = CGRectMake(0 , 0, 320 ,100);
if([indexPath row] == [cells count] )//numberOfRowsInSection中我返回的是[cells count]+1,最后有一个“加载更多。。。”项
{
cell = [tableView dequeueReusableCellWithIdentifier: tag1];
if( cell == nil )
{
cell = [[[UITableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier: tag1] autorelease];
cell.frame = cellFrame;
cell.backgroundColor = [UIColor clearColor];
//界面加载
cell.textLabel.frame = cellFrame;
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.tag = 50;
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(75,40,24,24)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.tag = 51;
[cell.contentView addSubview: activityIndicator];
[activityIndicator release];
}
//数据加载
if([indexPath row] == [items count]) //最后一条
{
UILabel *more = (UILabel *)[cell.contentView viewWithTag: 50];
more.text = @"已经是最后一条";
UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[cell.contentView viewWithTag:51];
[activity stopAnimating];
}
else
{
UILabel *more = (UILabel *)[cell.contentView viewWithTag: 50];
more.text = @"正在加载更多……";
UIActivityIndicatorView *activity = (UIActivityIndicatorView *)[cell.contentView viewWithTag:51];
[activity startAnimating];
}
}
else
{
cell = [tableView dequeueReusableCellWithIdentifier: tag];
if(cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier: tag] autorelease];
cell.frame = cellFrame;
cell.backgroundColor = [UIColor clearColor];
//界面加载
RWXZCellView *cellView = [[RWXZCellView alloc] initWithFrame:cellFrame];
cellView.backgroundColor = [UIColor clearColor];
cellView.tag = 100;
[cell.contentView addSubview:cellView];
[cellView release];
}
//加载数据
RWXZCellView *cellView =(RWXZCellView *)[cell.contentView viewWithTag:100];
[cellView setItemInfo:[cells objectAtIndex:[indexPath row]]];
}
return cell;
}
这样就不会出现重叠啦!