本文介绍: 也就是说,先运行scrollToItemAtIndexPath滑动方法然后绘制cell,这样当然就看不到滑动效果,因为调用顺序反了。所以,应该collectionView刷新完毕之后,再去调滑动方法。但是运行之后发现生效,也就是没有按照预期,滑动到想要的位置。…

最近在做一个日历相关需求日历控件是采用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;
}

原文地址:https://blog.csdn.net/u010545480/article/details/125905100

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_17833.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注