UICollectionView setLayout:animated: not preserving zIndex

前端 未结 7 1995
既然无缘
既然无缘 2021-02-01 20:12

I\'ve noticed that when calling setLayout:animated in a UICollectionView to switch between two layouts, the currently visible cell doesn\'t adhere to t

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-01 20:41

    I've managed to get the behaviour I'm after by using a combination grimfrog and Charlie Elliott's responses.

    Charlie Elliott's solution got the correct final outcome for the items in the collection view but there was still a snapping effect on the zIndex during the animation.

    grimfrog's solution provided the correct look but had the problem of the zIndex still being incorrect after the layout change, despite looking correct.

    The combination of the two, while not a great solution, does work and does use the supported transform and zIndex properties of the UICollectionViewLayoutAttributes

    In my layout, I have

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

    I won't make this as the correct answer just yet as I'm sure there must be another way to solve this, but I'm interested to see if this solves the problem for others as well.

提交回复
热议问题