App Face
App Face

Reputation: 81

How can I update a UIView's position and size in reference to it's superview's position and size? [Swift]

I have a superview with another subview inside of it. The subview has constraints set to it to be centered in the superview and half the size of the superview.

The position and size of the superview are being changed when a button is clicked, but the position and size of the subview is not being changed with it. I tried using UIView.updateConstraints(), but it is not repositioning it or resizing it.

So my question is:

What would be the best way to resize and reposition the subview with respect to the superview?

Thank you!

Here is the code:

func updateTimerFormat() {
        minutesContainer.frame.size.width *= 0.75
        minutesContainer.frame.size.height *= 0.75
        minutesContainer.center.x = view.center.x
        minutesContainer.center.y = view.center.y * 1.5 - 30

        // The minutes label is the subview of the minutesContainer
        minutesLabel.updateConstraints()
    }

Upvotes: 2

Views: 1925

Answers (3)

Hugo
Hugo

Reputation: 1152

You should not to call updateConstraints(), because I do not think your view's constraints need to be updated.

You just need to change SuperView's size or position. Then your view can automatically set the size and position, because you set their constraints before.

enter image description here This is a demo.https://github.com/cythb/iOSIssues/tree/master/2_AjustSizeDemo

constraints of subview

Constraint subview(yellow) center to superview(green) center. Constraint size is half of the superview(green).

When you click button, you don't do anything else,just change the size of superview.

Upvotes: 1

Buu Bui
Buu Bui

Reputation: 154

1/ Connect minutesContainer constraints to your ViewController:

@IBOutlet weak var widthConstraint: NSLayoutConstraint!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var centerYConstraint: NSLayoutConstraint!

2/ Change your updateTimerFormat method:

func updateTimerFormat() {
    widthConstraint.constant *= 0.75
    heightConstraint.constant *= 0.75
    centerYConstraint.constant = view.center.y * 0.5 - 30
  }

Upvotes: 0

Muzahid
Muzahid

Reputation: 5186

There are two ways-

  1. Implement the func layoutSubviews(). This method is called when super view frame become change. In this method you can change your subviews frame.

  2. Second option is that use autolayout during configure the subviews

Upvotes: 0

Related Questions