0

I simplify my problem to be like just an UIView on ViewController like the image below:

enter image description here

I drag the aspect ratio constraint from storyboard to ViewController code, and named aspectRatioConstraint.

I want that purple view will have the aspect ratio 1:1 when I run the app, so in viewDidLoad I set aspectRatioConstraint.constant = 1 (before running the aspect ratio is 343:128)

but nothing happened when I run the app. the aspect ration doesn't change to 1:1, what went wrong in here ?

sarah
  • 3,819
  • 4
  • 38
  • 80

3 Answers3

1

As the multiplayer is get only property we can't change its value instead we can change the constant property.

open var multiplier: CGFloat { get }

From the constraints menu:

enter image description here

First Item = (Multiplier * Second Item) + Constant

View.Height = ((128/343) * View.Width) + 0

In other words, 343 = (0.373 * 128) + x

As multiplier has to be changed from 0.373 to 1

(View.Height - constant) / View.width = Multiplier

(343 - x) / 128 = 1

x = 343 - 128

x = 215

aspectRatioConstraint.constant = 215
yourView.layoutIfNeeded()
Sateesh Yemireddi
  • 4,289
  • 1
  • 20
  • 37
1

As mentioned, the Aspect Ratio is really the constraint's Multiplier ... which is a "get only" property.

You can use a NSLayoutConstraint extension to change the Multiplier (found here: https://stackoverflow.com/a/33003217/6257435):

extension NSLayoutConstraint {
    /**
     Change multiplier constraint

     - parameter multiplier: CGFloat
     - returns: NSLayoutConstraint
    */
    func setMultiplier(multiplier:CGFloat) -> NSLayoutConstraint {

        NSLayoutConstraint.deactivate([self])

        let newConstraint = NSLayoutConstraint(
            item: firstItem,
            attribute: firstAttribute,
            relatedBy: relation,
            toItem: secondItem,
            attribute: secondAttribute,
            multiplier: multiplier,
            constant: constant)

        newConstraint.priority = priority
        newConstraint.shouldBeArchived = self.shouldBeArchived
        newConstraint.identifier = self.identifier

        NSLayoutConstraint.activate([newConstraint])
        return newConstraint
    }
}

Now, in viewDidLoad(), you can call:

aspectRatioConstraint = aspectRatioConstraint.setMultiplier(multiplier: 1.0)
DonMag
  • 69,424
  • 5
  • 50
  • 86
0

Need to integrate self.view.layoutIfNeeded() before and after changing the view contstraint constant.

user1376400
  • 614
  • 1
  • 4
  • 8