UICollectionView

1,131 阅读1分钟

比较常用的方法

1、删除或者添加表格
self.collectionView.performBatchUpdates({ 
        
        self.viewModel.cards.remove(at: indexPath.row) // 先移除数据源,不然数目不一致会崩溃
        self.collectionView.deleteItems(at: [indexPath])
    }, completion: { finish in
        if finish {  // 刷新表格,不然indexPath会出错
            self.collectionView.reloadItems(at: self.collectionView.indexPathsForVisibleItems)
        }
    })
2、当contentSize < frame的时候保持滑动
alwaysBounceVertical = true
3、设置contentOffset的时候需要注意的代理方法
scrollViewDidScroll(_ scrollView: UIScrollView) // 设置的时候是会触发这个方法的

scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) // 使用set方法,动画结束后会调用这个方法
4、 footerView一直保持在底部(不成熟方法)
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    /**
     *  1、获取最后一个单元格的最大Y值  <竟然获取不到!!!>
     *  2、如果最大Y值大于 (屏幕高度 - 底部高度 - 30)= 内切高度
     *  3、如果最大Y值小于 内切高度 = (屏幕高度 - 最大Y值 - 底部高度)
     */
    PAHomeViewCell *lastCell = (PAHomeViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:1]];
    CGFloat lastCellMaxY = CGRectGetMaxY(lastCell.frame);
    CGFloat footerY = _footerView.frame.origin.y;
    CGFloat bottomInset;
    if (footerY < (SCREEN_HEIGHT - _footerView.height)) {
        bottomInset = (SCREEN_HEIGHT - _footerView.height - footerY) + 30;
    }else if(footerY > SCREEN_HEIGHT - _footerView.height){
        bottomInset = 30;
    }else{
        return;
    }
    _layout.sectionInset = UIEdgeInsetsMake(30, 20, bottomInset, 20);
}

5、注意事项
做动画的时候,如果高度变得比现在小  选中下面的cell会消失 变高不会 

设置contentoffset的时候要在reload之后设置,不然可能会出现BUG