2017-06-04 50 views
0

我下面的代碼centerize它: -如何在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]; 

這是不按預期工作。由於我無法在加載collectionview之後集中確切的單元格。何時何地我應該將此方法稱爲[self centerUpNext:self.upNextIndexPath];

+0

首先,你得到的'indexPath'你想* *獲得?如果在'viewWillAppear'中執行'print(self.upNextIndexPath)',它是否顯示了你想要居中的正確單元格? – DonMag

回答

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

}

相關問題