Custom Aspect Ratio with AutoLayout

2019-01-30 18:17发布

问题:

Let's say I have a UIView that contains a child UIView which has to be 4:3. I want to solve this problem using AutoLayout in code.

I've been struggling with AutoLayout but I haven't figured out yet how to do this.

Do you know how to solve this problem?

Thank you very much.

I attach an image to explain better what I mean. http://d.pr/i/d0Oc

回答1:

I figured out.

//Given a childView... 
NSLayoutConstraint *constraint =[NSLayoutConstraint
                           constraintWithItem:childView
                           attribute:NSLayoutAttributeWidth
                           relatedBy:NSLayoutRelationEqual
                           toItem:childView
                           attribute:NSLayoutAttributeHeight
                           multiplier:4.0/3.0 //Aspect ratio: 4*height = 3*width
                           constant:0.0f];
            [childView addConstraint:constraint];


回答2:

Here is the syntax for Swift 3:

NSLayoutConstraint(
  item: item,
  attribute: .width,
  relatedBy: .equal,
  toItem: item,
  attribute: .height,
  multiplier: width / height,
  constant: 0)


回答3:

I have try all answers above but didn't work, and this is my solution with swift 3:

let newConstraint = NSLayoutConstraint(item: yourView, attribute: .width, relatedBy: .equal, toItem: yourView, attribute: .height, multiplier: 560.0/315.0, constant: 0)
yourView.addConstraint(newConstraint)
NSLayoutConstraint.activate([newConstraint])  
NSLayoutConstraint.deactivate(yourView.constraints)
yourView.layoutIfNeeded()