UICollectionView setLayout:animated:不保留zIndex

sam*_*age 19 z-index ios uicollectionview

我注意到当调用setLayout:animateda UICollectionView在两个布局之间切换时,当前可见的单元格不符合zIndex它的布局属性已被设置layoutAttributesForItemAtIndexPath:.

例如,如果我有一个UICollectionViewwith UICollectionViewFlowLayout,则将其设置minimumLineSpacing为负数,以便单元格重叠,然后zIndex在每个单元格上设置一个高于前一个单元格的单元格,然后看起来好像单元格从下往上堆叠.

但是,如果我将布局设置为另一个布局然后返回到原始布局,则会中断.就好像当前可见的单元格不会监听zIndex并放置在其他单元格的顶部.如果我在屏幕外滚动单元格然后重新打开它就在正确的位置.

小智 10

我曾经也有过一样的问题.切换布局将忽略单元格的zIndex.

我已经设法通过在z轴上应用这样的翻译使其"看起来正确":

attributes.transform3D = CATransform3DMakeTranslation(0, 0, indexPath.row);
Run Code Online (Sandbox Code Playgroud)

但它只是一个视觉修复,如果您尝试单击该项目,您将意识到zIndex仍然是错误的,直到它通过在屏幕外滚动来回收.

  • 如果你和zindex并排使用它就是一个解决方案 - 即.`attributes.transform3D = CATransform3DMakeTranslation(0,0,indexPath.row); attributes.zIndex = indexPath.row;` - 至少使用两者都适合我. (2认同)

sam*_*age 8

通过使用组合grimfrog和Charlie Elliott的回答,我设法得到了我所追求的行为.

Charlie Elliott的解决方案为集合视图中的项目获得了正确的最终结果,但在动画期间仍然存在对zIndex的捕捉效果.

grimfrog的解决方案提供了正确的外观,但在布局更改后仍然存在zIndex的问题,尽管看起来正确.

两者的结合虽然不是一个很好的解决方案,但确实可以使用UICollectionViewLayoutAttributes支持的转换和zIndex属性.

在我的布局中,我有

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
  NSArray *attributes = [super layoutAttributesForElementsInRect:rect];

  [attributes enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *attributes, NSUInteger idx, BOOL *stop) {
    attributes.zIndex = attributes.indexPath.item + 1;
  }];

  return attributes;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
  UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];

  attributes.transform3D = CATransform3DMakeTranslation(0, 0, attributes.indexPath.item);
  return attributes;
}
Run Code Online (Sandbox Code Playgroud)

我不会将此作为正确的答案,因为我确信必须有另一种方法来解决这个问题,但我很想知道这是否也解决了其他人的问题.


小智 6

尝试:

// In UICollectionViewCell subclass
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    [super applyLayoutAttributes:layoutAttributes];
    // Setting zPosition instead of relaying on
    // UICollectionView zIndex management 'fixes' the issue
    self.layer.zPosition = layoutAttributes.zIndex;
}
Run Code Online (Sandbox Code Playgroud)


小智 2

尝试在以下位置设置 z-index:

- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath;
- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingItemAtIndexPath:(NSIndexPath *)itemIndexPath;
Run Code Online (Sandbox Code Playgroud)