Slava Slava - 1 year ago 105
iOS Question

Change size and position of objects programmatically

I'm trying to change size and position of some objects in viewDidLayoutSubviews(). Method fixPositions() is called, but all changes apply only after I go to the next screen.

Here is my code:

override func viewDidLayoutSubviews() {
let width = filterMainView.frame.width / 5

filterView.frame = CGRectMake(0.0, 0.0, width, 50.0)

fixPositions(filterSubview, image: filterImage, button: filterButton, width: width)

func fixPositions(mainView: UIView, image: UIImageView, button: UIButton, width: CGFloat) {
let buttonFrame = CGRectMake(0.0, 0.0, width, 50.0)

button.frame = buttonFrame
mainView.frame = buttonFrame
image.frame = CGRectMake((width - 30.0)/2, 10.0, 30.0, 30.0)

Besides, filterView works fine, it is changed immediately. What can be wrong with this method?

Answer Source

Calling self.layoutIfNeeded() after that your element frame has been changed will update the frame. It's better to use it when the frame is always changing.