UICollectionView 显示隐藏动画问题

UICollectionView show hide animation issue

我在隐藏 UICollectionView 时遇到动画问题。显示动画效果很好,但是当我执行隐藏动画时,它会立即隐藏没有动画的集合视图。这是代码:

@objc func openMenu(sender: UIButton) {
        if sender.tag == 1 {
            self.buttonView.tag = 2
            self.arrow.image = UIImage(named: "arrowUp.png")
            UIView.animate(withDuration: 0.7, animations: {
                self.moduleView.frame.size.height = UIScreen.main.bounds.size.height - self.frame.size.height
            }, completion: { _ in
            })
        } else {
            self.buttonView.tag = 1
            self.arrow.image = UIImage(named: "arrowDown.png")
            UIView.animate(withDuration: 0.7, animations: {
                self.moduleView.frame.size.height = 0
            }, completion: { _ in
            })
        }
    }  

输出:

奇怪的是,我用一个简单的 UIView 替换了集合视图并且它工作正常。从下到上动画效果完美。代码:

@objc func openMenu(sender: UIButton) {
        if sender.tag == 1 {
            self.buttonView.tag = 2
            self.arrow.image = UIImage(named: "arrowUp.png")
            UIView.animate(withDuration: 0.7, animations: {
                self.testView.frame.size.height = UIScreen.main.bounds.size.height - self.frame.size.height
            }, completion: { _ in
            })
        } else {
            self.buttonView.tag = 1
            self.arrow.image = UIImage(named: "arrowDown.png")
            UIView.animate(withDuration: 0.7, animations: {
                self.testView.frame.size.height = 0
            }, completion: { _ in
            })
        }
    }  

输出:

问题:为什么这对 UICollectionView 不起作用?

初始化:

UICollectionView :

self.moduleView = ModulesCollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0), collectionViewLayout: UICollectionViewLayout())  
self.parentView.addSubView(self.moduleView)  

用户界面视图:

self.testView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0))  
self.parentView.addSubView(self.testView)

您需要使用 layoutSubViews() 方法来获得正确的动画效果。请更改您的代码如下:

@objc func openMenu(sender: UIButton) {
    if sender.tag == 1 {
        self.buttonView.tag = 2
        self.arrow.image = UIImage(named: "arrowUp.png")
        UIView.animate(withDuration: 0.7, animations: {
            self.moduleView.frame.size.height = UIScreen.main.bounds.size.height - self.frame.size.height
            // Add this line
            self.moduleView.layoutSubviews()
        }, completion: { _ in
        })
    } else {
        self.buttonView.tag = 1
        self.arrow.image = UIImage(named: "arrowDown.png")
        UIView.animate(withDuration: 0.7, animations: {
            self.moduleView.frame.size.height = 0
            // Add this line
            self.moduleView.layoutSubviews()
        }, completion: { _ in
        })
    }
}