Animate uicollectionview cells on selection

2019-02-18 16:40发布

I have created a customlayout and set my cells position attribute in layoutAttributesForItemAtIndexPath like this

attributes.center = CGPointMake((size.width/2 - 100) + 100, (size.height/2 - 150) +100);

I would like to animate a cell when it is selected. replicating the kind of animations we get with the initialLayoutAttributesForAppearingItemAtIndexPath & finalLayoutAttributesForDisappearingItemAtIndexPath.

I'd like to do this when a cell is selected and de-selected.

so for instance:

Cell A is in position 0,0. Cell B is in position 50,100. If I select cell B I'd like to animate it to 0,0. and at the same time animate cell A to 50,100. basically switching positions, but animated.

2条回答
做个烂人
2楼-- · 2019-02-18 16:59

Maybe a different approach. Just override isSelected in the collectionViewCell.

 override var isHighlighted: Bool {
    didSet {
        if isHighlighted {
            UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
                // animate highlight
            }, completion: nil)
        } else {
            UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
                // animate unHighligh
            }, completion: nil)
        }
    }
}

In this post UICollectionView: Animate cell size change on selection you can see an example on how to animate a size change.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-18 17:06

I'm animating the attributes by using didSelectItemAtIndexPath in my UICollectionViewDelegate:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_collectionView.collectionViewLayout invalidateLayout];
    UICollectionViewLayoutAttributes *newAttributes = [_collectionView layoutAttributesForItemAtIndexPath:indexPath];

    //use new attributes for animation
}
查看更多
登录 后发表回答