UICollectionView显示隐藏动画问题

时间:2018-06-13 12:58:26

标签: ios swift uiview uicollectionview ios-animations

我在隐藏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
            })
        }
    }  

输出

enter image description here

奇怪的是,我用简单的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
            })
        }
    }  

输出

enter image description here

问题:为什么这不适用于 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)  

UIView:

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

1 个答案:

答案 0 :(得分:1)

您需要使用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
        })
    }
}