通过动画和中心更改宽度 UIView

Ras*_*iri 5 uiviewanimation ios swift

我有一个视图,需要通过动画将宽度从 100 更改为 200。

UIView.animate(withDuration: 5
            ,animations: {
                    self.backgroundPlaceHolderView.frame.size.width += 200
})
Run Code Online (Sandbox Code Playgroud)

运行此代码时,我的视图更改宽度,但我需要从中心更改宽度,但此代码将视图向右增加 在此处输入图片说明

gul*_*hki 8

如果您确实需要使用框架来完成此操作,这里有一个代码片段:

UIView.animate(withDuration: 1, animations: {
        self.backgroudPlaceHolderView.frame.origin.x -= 100
        self.backgroudPlaceHolderView.frame.size.width += 200
    })
Run Code Online (Sandbox Code Playgroud)


小智 6

在我看来,如果您从操纵框架转向操纵约束,这会更容易、更清晰。

  1. 在 InterfaceBuilder 中(或以编程方式)UIView水平居中。
  2. 输出宽度限制(从 100 开始)。

当您想增加宽度时,UIView可以执行以下操作;

view.layoutIfNeeded() // always make sure any pending layout changes have happened

widthConstraint.constant = 200

UIView.animate(withDuration: 0.3, animations: {
    self.view.layoutIfNeeded()
})
Run Code Online (Sandbox Code Playgroud)

自动布局将为您处理剩下的事情。您的视图水平居中,因此它应该从中心扩展。