UIView自下而上的动画问题

时间:2018-06-07 12:20:20

标签: ios swift uiview uiviewanimation

这是一个简单的函数,用于从上到下动画视图,反之亦然(如果是从上到下的动画,则是从下到上的动画):

@objc func openMenu(sender: UIButton) {
        if sender.tag == 1 {
            self.buttonView.tag = 2
             self.moduleView = ModulesCollectionView(frame: CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: 0), collectionViewLayout: UICollectionViewLayout())
            self.window?.addSubview(self.moduleView)
            UIView.animate(withDuration: 0.7, animations: {
                self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - self.frame.size.height - 22)
            }, completion: { _ in

            })

        } else {
            self.buttonView.tag = 1
            UIView.animate(withDuration: 3, animations: {
                self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: 0)
            }, completion: { _ in
                self.moduleView.removeFromSuperview()
            })
        }
    }  

顶级动画效果很好,视图在0.7秒内从上到下愉快地动画。但是,从下到上的动画不会发生。视图立即被删除。这是我得到的结果:

enter image description here

但是我希望动画从底部到顶部都是干净的。就像here一样。

中学:我最终计划实现的是PullUpController,其中包含完全相反的动画。因此,如果有人知道类似的库(下拉拖动)可以共享那里的输入。

更新问题出现在UICollectionView上。我用简单的UIView替换了collectionView,它完美无缺。

2 个答案:

答案 0 :(得分:2)

您应该在动画块结束后尝试使用layoutSubViews()方法。像这样更改动画块。

if if block:

self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - self.frame.size.height - 22)
self.moduleView.layoutSubviews()

对于else阻止:

self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: 0)
self.moduleView.layoutSubviews()

答案 1 :(得分:0)

这是示例代码,希望它会有所帮助。

显示视图:

self.containerView = ModulesCollectionView(frame: UIScreen.main.bounds)
self.containerView.center = CGPoint(x: self.view.center.x,
        y: self.view.center.y + self.view.frame.size.height)
self.window?.addSubview(self.moduleView)
self.window?.bringSubview(toFront: self.moduleView)
self.window?.endEditing(true)
UIView.animate(withDuration: 0.3, delay: 0.0,
    usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0,
    options: .allowAnimatedContent, animations: {
    self.moduleView.center = self.view.center
}) { (isFinished) in
    self.view.layoutIfNeeded()
}

隐藏视图:

UIView.animate(withDuration: 0.7, delay: 0.0,
    usingSpringWithDamping: 1, initialSpringVelocity: 1.0,
    options: .allowAnimatedContent, animations: {
    self.moduleView.center = CGPoint(x: self.view.center.x,
    y: self.view.center.y + self.view.frame.size.height)
}) { (isFinished) in
    self.moduleView.removeFromSuperview
}