Search code examples
swiftuicollectionviewautolayout

How to avoid fade animation in UICollectionView when update constraints


When update constraints for UICollectionView (scale down or upscale), items are (scale down or upscale) with fade animation. How to avoid this?

// activating constraints:
containerLeft = containerView.leftAnchor.constraint(equalTo: view.leftAnchor)
containerRight = containerView.rightAnchor.constraint(equalTo: view.rightAnchor)
containerTop =  containerView.topAnchor.constraint(equalTo: view.topAnchor)
containerBottom = containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)

containerLeft.isActive = true
containerRight.isActive = true
containerTop.isActive = true
containerBottom.isActive = true

Function for changing constraints:

func setinsetsForContainer(left: CGFloat, right: CGFloat, top:CGFloat, bottom:CGFloat?){
        containerLeft.constant = left
        containerRight.constant = -right
        containerTop.constant = top
        containerBottom.constant = -bottom!
}

animatedupdateConstraints:

setinsetsForContainer(left: 20, right: 20, top:100, bottom:100)
UIView.animate(withDuration: 2) {
 self.view.layoutIfNeeded()
}

Solution

  • just override this methods In UICollectionViewFlowLayout

    // disable fade animation in cells
        override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
            let attribute = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath)
            attribute?.alpha = 1
            return attribute
        }
    
        override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
            let attribute = super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath)
            attribute?.alpha = 1
            return attribute
        }
    
    //    disable fade animation in header/footer
        override func initialLayoutAttributesForAppearingSupplementaryElement(ofKind elementKind: String, at elementIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
            let attribute = super.initialLayoutAttributesForAppearingSupplementaryElement(ofKind: elementKind, at: elementIndexPath)
            attribute?.alpha = 1
            return attribute
        }
    
        override func finalLayoutAttributesForDisappearingSupplementaryElement(ofKind elementKind: String, at elementIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
            let attribute = super.finalLayoutAttributesForDisappearingSupplementaryElement(ofKind: elementKind, at: elementIndexPath)
            attribute?.alpha = 1
            return attribute
        }