Abdurrahman Mubeen Ali
Abdurrahman Mubeen Ali

Reputation: 1341

How to programmatically set a subview's frame to fit it inside its superview?

I need to programmatically do the following. How can I do this? The code should be dynamic enough to fit a portrait view inside landscape also. The views are not UIImageViews. enter image description here

Upvotes: 2

Views: 1188

Answers (2)

Wain
Wain

Reputation: 119021

If you don't mind including the AVFoundation framework in your project, you can use: AVMakeRectWithAspectRatioInsideRect(CGSize aspectRatio, CGRect boundingRect);

Its documentation states:

Returns a scaled CGRect that maintains the aspect ratio specified by a CGSize within a bounding CGRect.

It can be used as:

subview.frame = AVMakeRectWithAspectRatioInsideRect(subview.bounds.size, superview.bounds);

Parameters:

aspectRatio: The width and height ratio (aspect ratio) you want to maintain.

boundingRect: The bounding rectangle you want to fit into.

Upvotes: 3

clevin
clevin

Reputation: 79

float ratio = subView.bounds.size.height/subView.bounds.size.width;

[subView setFrame:CGRectMake(0,0,superView.bounds.size.width,superView.bounds.size.width*ratio)];
[subView setCenter:CGPointMake(superView.bounds.size.width/2,superView.bounds.size.height/2)];

Upvotes: 0

Related Questions