如果大家是做ios开发,相信大家都用过UITableView,UITableView是继承自UIScroller,是苹果公司为我们封装好的一套很好用的控件,对于UITableView的使用我就不一一讲述了。首先上图给大家看看
首先在UITableView中选中一个条目,,在UITableView滚动的时候会发现有的条目没勾选了,却默认勾选上。
这是UITableView内部返回cell代码实现
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cityId = @"cityId";
//1.先去缓存池中查找是否有满足条件的Cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cityId];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cityId];
}
//获取模型设置数据
XMCityGround *ground = self.outSideCityArray[indexPath.section];
XMLeaves *leaves = ground.leaves[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@ (%@)",leaves.cityName,leaves.countryName];
return cell;
}
解决方法1:
将获取cell方法中的
改为:
cell =[tableView cellForRowAtIndexPath:indexPath];
重用机制用的dequeReusableCellWithIdentifier方法意思就是“
出列可重用的cell”,因而只要将它换为
cellForRowAtIndexPath(只从要更新的cell的那一行取出cell),就可以不使用重用机制,因而问题就可以得到解决。这样做对于少量数据是可以解决问题的,如果对于数据大的就会浪费内存。
解决方法2:
将
static NSString *cityId = @"cityId";
改为
NSString *cityId = [NSString stringWithFormat:@"cityId%d%d",indexPath.section,indexPath.row];
这样对每个cell都绑定一个不重复的标识,重用机制是根据相同的标识符来重用cell的,标识符不同的cell不能彼此重用。于是我们将每个cell的标识符都设置为不同,就可以避免不同cell重用的问题了。
解决方法3:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cityId];
} else {
//删除cell的所有子视图
while ([cell.contentView.subviews lastObject] != nil)
{
[(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
这个方法是通过删除重用的cell的所有子视图,从而得到一个没有特殊格式的cell,供其他cell重用