Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
}
like image 717
Паша Матюхин Avatar asked Oct 27 '25 08:10

Паша Матюхин


1 Answers

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
    }
like image 97
Паша Матюхин Avatar answered Oct 29 '25 00:10

Паша Матюхин



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!