xcode CollectionViewController scrollToItemAtIndexPath not working

前端 未结 9 814
故里飘歌
故里飘歌 2021-02-01 03:06

I have created a CollectionView Control and filled it with images. Now I want to scroll to item at a particular index on start. I have tried out scrollToItemA

9条回答
  •  有刺的猬
    2021-02-01 03:37

    U can do this and on viewDidLoad method

    just make call preformBatchUpdates

    [self performBatchUpdates:^{
            if ([self.segmentedDelegate respondsToSelector:@selector(segmentedBar:selectedIndex:)]){
                [self.segmentedDelegate segmentedBar:self selectedIndex:_selectedPage];
            }
        } completion:^(BOOL finished) {
            if (finished){
                [self scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_selectedPage inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
            }
    
        }];
    

    In my case my subclass CollectionView has a property selectedPage, and on a setter of this property i call

    - (void)setSelectedPage:(NSInteger)selectedPage {
        _selectedPage = selectedPage;
        [self performBatchUpdates:^{
            if ([self.segmentedDelegate respondsToSelector:@selector(segmentedBar:selectedIndex:)]){
                [self.segmentedDelegate segmentedBar:self selectedIndex:_selectedPage];
            }
        } completion:^(BOOL finished) {
            if (finished){
                [self scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_selectedPage inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
            }
    
        }];
    }
    

    In view controller i calling this by code

    - (void)viewDidLoad {
        [super viewDidLoad];
        self.navigationBar.segmentedPages.selectedPage = 1;
    }
    

提交回复
热议问题