OGeek|极客世界-中国程序员成长平台

标题: ios - 如何确保更改的 collectionview 单元格出现在手机屏幕的中心? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:47
标题: ios - 如何确保更改的 collectionview 单元格出现在手机屏幕的中心?

场景:我有一个每 15 秒重新加载一次的 Collection View 。此 Collection View 中的单元格数量没有限制,但是一次只能突出显示一个单元格。只有一个部分,collectionview 水平滚动。我需要确保突出显示的单元格始终位于手机屏幕的中央。例如,如果突出显示第 24 个单元格,则必须一直滚动直到找到它,这将是一种糟糕的用户体验。但是,当 Collection View 在另外 15 秒内重新加载时,可能会突出显示一个完全不同的单元格。

See bottom portion of the image for a better idea of highlighted and unhighlighted cells.

这是我尝试过的与突出显示的单元格的索引路径相关的想法,并确保它位于手机屏幕的中心。

- (UICollectionViewCell *)collectionViewUICollectionView *)collectionView cellForItemAtIndexPathNSIndexPath *)indexPath {

  EZPlayerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier"layerCellID" forIndexPath:indexPath];

  NSDictionary *rowData = [[_gameBoardDictionary objectForKey"players"] objectAtIndex:indexPath.row];

  if ([[rowData objectForKey"possession"] integerValue] == 1) {
     cell.isHighlighted = YES;
  } else {
     cell.isHighlighted = NO;
  }

  if (cell.isHighlighted) {

     self.highlightedCellIndexPath = [self.collectionView indexPathForCell:cell];

  } else {

  }

  return cell;
}

- (void)viewDidLayoutSubviews {

  [self.collectionView scrollToItemAtIndexPath:self.highlightedCellIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}

我尝试了很多东西,但这应该为我的思路提供引用。任何帮助,将不胜感激。非常感谢!



Best Answer-推荐答案


请为 Collection View 的“contentSize”键路径添加一个观察者。

[self.collectionView addObserver:self forKeyPath"contentSize" options:NSKeyValueObservingOptionOld context:NULL];

然后您可以在 observeValueForKeyPath 方法中移动滚动代码。

- (void)observeValueForKeyPathNSString *)keyPath ofObjectid)object changeNSDictionary  *)changeDict contextvoid *)context
{
  [self.collectionView scrollToItemAtIndexPath:self.highlightedCellIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

关于ios - 如何确保更改的 collectionview 单元格出现在手机屏幕的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940003/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4