40

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

brainjam
  • 18,863
  • 8
  • 57
  • 82
JaviAlgaba
  • 1,433
  • 1
  • 13
  • 13

3 Answers3

96

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];
dlinsin
  • 19,249
  • 13
  • 42
  • 53
JaviAlgaba
  • 1,433
  • 1
  • 13
  • 13
  • Is this doable from interface builder too? – fabb Sep 18 '14 at 09:20
  • 1
    Yes it is since Xcode 6! In the Pin Tool there now is an option for Aspect. – fabb Sep 18 '14 at 09:35
  • 3
    I think it needs to swap NSLayoutAttributeHeight and NSLayoutAttributeWidth. Right now it says 3:4 and not 4:3. – Evgenii Nov 18 '14 at 06:08
  • 2
    Also, a good thing to add here, is that you cannot change the multiplier of constraints once they're created - the multiplier property's read-only. One's not able to change the multiplier even by using key paths. The way to proceed is to remove the constraint at hand and recreate it with the new multiplier. – D6mi Jan 18 '16 at 11:30
1

Here is the syntax for Swift 3:

NSLayoutConstraint(
  item: item,
  attribute: .width,
  relatedBy: .equal,
  toItem: item,
  attribute: .height,
  multiplier: width / height,
  constant: 0)
Bart van Kuik
  • 4,704
  • 1
  • 33
  • 57
user1615898
  • 1,185
  • 1
  • 10
  • 20
0

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()
tuandapen
  • 284
  • 4
  • 6