9

I have a view and need change width from 100 to 200 by animation.

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

when running this code, my view change width, but I need a change in width from the center, but this code increase view to the right enter image description here

Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78

3 Answers3

7

If you really need to do it with frames, here's a code snippet:

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

If you moved from manipulating the frame to manipulating constraints this would be easier and cleaner in my opinion.

  1. In the InterfaceBuilder (or programmatically) center your UIView horizontally.
  2. Outlet your width constraint (which would begin at 100).

When you want to increase the width of your UIView you can do the following;

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

widthConstraint.constant = 200

UIView.animate(withDuration: 0.3, animations: {
    self.view.layoutIfNeeded()
})

Autolayout will take care of the rest for you. Your view is centered horizontally so it should expand from the center.

Daniel T-D
  • 665
  • 6
  • 8
2

You should have that backgroundPlaceHolderView constrained on the centerX. It's probably anchored on the left.

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37