iOS scrollToItemAtIndexPath方法不生效

最近在做一个日历相关的需求,日历控件是采用UICollectionView来实现的,进入到日历界面,需要自动滑动到当前的月份,代码如下:

- (instancetype)initWithFrame:(CGRect)frame
{
    
    
    self = [super initWithFrame:frame];
    if(self){
    
    
        [self loadData];
        [self collectionView];
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:100 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    return self;
}

但是运行之后发现不生效,也就是没有按照预期,滑动到想要的位置。
通过断点调试发现,会先调用:

  [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:100 inSection:0]

然后再调用:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    CalendarBaseCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"CalendarBaseCell" forIndexPath:indexPath];
    cell.model = self.listData[indexPath.row];
    return cell;
}

也就是说,先运行了 scrollToItemAtIndexPath 滑动的方法,然后再绘制 cell,这样当然就看不到滑动的效果,因为调用顺序反了。所以,应该在collectionView 刷新完毕之后,再去调滑动的方法。
正确代码如下:

- (instancetype)initWithFrame:(CGRect)frame
{
    
    
    self = [super initWithFrame:frame];
    if(self){
    
    
        [self loadData];
        [self collectionView];
        
        [self.collectionView performBatchUpdates:^{
    
    
            //这里执行刷新语句
            [self.collectionView reloadData];
        } completion:^(BOOL finished) {
    
    
            //这里获取刷新结束回调
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:page*7 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
        }];
    }
    return self;
}

猜你喜欢

转载自blog.csdn.net/u010545480/article/details/125905100
今日推荐