【问题标题】:How to centerize a UICollectionView cell after it has been loaded?加载后如何将 UICollectionView 单元格居中?
【发布时间】:2017-06-04 14:51:33
【问题描述】:

下面我的代码使其居中:-

- (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];

【问题讨论】:

  • 首先,您是否获得了您想要获得的indexPath?如果在viewWillAppear 中执行print(self.upNextIndexPath),它是否显示了您想要居中的正确单元格?

标签: ios objective-c uicollectionview


【解决方案1】:

我认为使用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];
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多