首页 > 解决方案 > 在 Swift 中用动画改变 UIView 的超级视图

问题描述

我有一个VideoView(它是 的子视图UIView)。

默认情况下,它被添加到UIView屏幕角落的小视图中(我称之为ParrentView1)。

我有一个缩小按钮VideoView。此按钮执行从更大的视图中删除VideoView并将ParentView1其添加到更大视图(称为ParrentView2)的操作。

当我执行下面的代码时,它可以工作,但动画很奇怪。ParrentView1我所需要的只是从to缩小动画ParrentView2。这是我的代码:

VideoView.removeFromSuperview()
ParrentView2.addSubview(VideoView)
UIView.animate(withDuration: 0.8, delay: 0,
               usingSpringWithDamping: 1,
               initialSpringVelocity: 1,
               options: .curveEaseOut,
               animations: {

                VideoView.frame = ParrentView2.bounds
}, completion: nil)

谢谢你的帮助

标签: iosswiftanimation

解决方案


可能的原因是当将它添加到另一个视图时,它被分配了一个不同的框架。解决方案是确保动画从原始位置开始。就像是:

CGRect originalRect = ParrentView2.convert(VideoView.frame, from:VideoView.superView);

VideoView.removeFromSuperview()
ParrentView2.addSubview(VideoView)
VideoView.frame = originalRect;
UIView.animate(withDuration: 0.8, delay: 0,
               usingSpringWithDamping: 1,
               initialSpringVelocity: 1,
               options: .curveEaseOut,
               animations: {

                VideoView.frame = ParrentView2.bounds
}, completion: nil)

一个改进点:请注意,在 Swift 中习惯上以小写字母开头变量名。当他们不这样做时,它会变得混乱。


推荐阅读