0
点赞
收藏
分享

微信扫一扫

UICollectionView嵌套TableView时的注意事项

梦想家们 2021-09-23 阅读 35

开发中,需要实现三个水平滑动页面,其中一个页面是UITableView,页面需要每个2秒刷新一次,另外两个是普通UIView.
实现思路如下:三个页面的水平滑动用UICollectionView实现,其中的UITabelView嵌套在UICollectionCell的contentView里面,其刷新用NSTimer来实现.
下面是tableView中的代码

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self timer];
    }
    return self;
}
- (void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
}
- (NSTimer *)timer{
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerDid) userInfo:nil repeats:YES];
    }
    return _timer;
}
- (void)timerDid{
    [self reloadData];
    NSLog(@"timer");
}

根据实际测试,当在滑动collectionView时,并不会调用tableView的dealloc方法,并且控制台一直打印timer的信息.也就是说timer对象和tableView对象并不会销毁.这是因为collectionView在滑动时的重用机制造成的,放入缓存池中的collectionViewCell对象并没有销毁,也就不会调用dealloc方法,而timer执行的方法又有对self的引用,所以tableView并没有销毁.当用户反复滑动collectionView时,会多次创建tableView,造成大量的资源浪费,降低手机性能.
解决方法,是在collectionView中的tableView页面进入缓存池后,手动调用 [self.timer invalidate]方法,强行终止timer,collectionView中的方法如下

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        //将cell重用时的其他控件移除
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//        cell.contentView.backgroundColor = [UIColor whiteColor];
        ZDTabelView *tableView = [[ZDTabelView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
        tableView.backgroundColor = [UIColor greenColor];
        self.tableView = tableView;
        [cell.contentView addSubview:tableView];
        
    }else if(indexPath.row == 1){
        [self.tableView.timer invalidate];
        self.tableView.timer = nil;
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        cell.contentView.backgroundColor = [UIColor grayColor];
    }else{
        [self.tableView.timer invalidate];
        self.tableView.timer = nil;
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        cell.contentView.backgroundColor = [UIColor redColor];
    }
    return cell;
}

Tips:在调用timer的invalidate方法后,timer有可能并没有变成nil,所以需要显式的指定.
下面是github上的Demo:

https://github.com/zhudong10/collectionViewWithTableView.git
举报

相关推荐

0 条评论