如何在加载UICollectionView单元后将其居中?

时间:2017-06-04 14:51:33

标签: ios objective-c uicollectionview

下面我的代码将其集中化: -

- (void)centerUpNext:(NSIndexPath*)indexPath {
    //[super viewDidLayoutSubviews];
    [self.collectionView2 scrollToItemAtIndexPath:indexPath
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

这是我分配indexPath值的方法: -

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath

    if(result == NSOrderedDescending)
        {
            NSLog(@"reminderTime is later than systemTime");
            self.upNextIndexPath = indexPath;
        }

我将从viewWillAppear

中调用它
-(void) viewWillAppear:(BOOL)animated
[self centerUpNext:self.upNextIndexPath];

这不符合预期。因为我无法在收集集合视图后集中精确的单元格。我应该在何时何地调用此方法[self centerUpNext:self.upNextIndexPath];

1 个答案:

答案 0 :(得分:0)

我认为使用KVO是最佳解决方案。

viewDidLoad中,您可以添加

[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:"contentSize"];

然后:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqual: @"contentSize"]) {
        if ([change[NSKeyValueChangeNewKey] CGSizeValue].height != 0 && [change[NSKeyValueChangeNewKey] CGSizeValue].width != 0) {
        [self centerUpNext:self.upNextIndexPath];
    }
}

}