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

问题描述 投票:1回答:3

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

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

运行此代码时,我的视图更改宽度,但我需要从中心更改宽度,但此代码将视图增加到右侧enter image description here

ios swift uiviewanimation
3个回答
2
投票

如果你真的需要使用框架,这里是一个代码片段:

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

3
投票

如果你从操纵框架转移到操纵约束,我认为这将更容易和更清洁。

  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()
})

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


1
投票

您应该将centerPlaceHolderView限制在centerX上。它可能锚定在左侧。

© www.soinside.com 2019 - 2024. All rights reserved.