Fab
Fab

Reputation: 836

Autoresize subviews when the frame of superview is modified

I have a green rectangle (viewA) with a inner red rectangle (viewB). If I try to modify the dimension of the viewA the viewB is not automatically changed.

I try to:

All these solution don't work.

This is my code:

@IBOutlet weak var viewA: UIView!

@IBOutlet weak var button: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func buttonAction(_ sender: Any) {
    viewA.autoresizesSubviews = true
    self.viewA.autoresizingMask = [.flexibleWidth, .flexibleHeight,.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin]
    viewA.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) // or frame instead of bounds
}

enter image description here enter image description here

Thanks to everyone.

EDIT:

I add the two views in the storyboard. Here you can see also the constraint of the viewB.

enter image description here

Upvotes: 1

Views: 1092

Answers (2)

Mahendra
Mahendra

Reputation: 8904

Don't mix up frame and auto layout of a view, both are behaving differently.

You need to do something like as follow.

Constrains for viewA

  • CenterX and CenterY
  • (Height or Width) and Aspect Ratio 1:1 (means equal width and equal height)

Constraints for viewB

  • Leading, Trailing, Top and Bottom to its superview (i.e. viewA)

Now you need to Create an @IBOutlet to the constraint you need to modify(of viewA).

@IBOutlet weak var const_height_viewA: NSLayoutConstraints!

So on button click you need to change only constraint's constant.

@IBAction func buttonAction(_ sender: Any) {
    const_height_viewA.constant = 250
    //changing height constraint of viewA will automatically updates viewB frame.
}

Note: No need to modify constraints of viewB as it will be automatically adjusted by given constraints.

For pictorial reference

enter image description here

Upvotes: 1

Skywalker
Skywalker

Reputation: 1586

You should not change the frame if you are using AutoLayout. If you are using AutoLayout, it is best to update the constraints to the values you want instead of changing the frame.

Notice the first point in the Rule of Thumb section from the docs.

Upvotes: 0

Related Questions