Hashira
Hashira

Reputation: 70

How can I resize an UIView by code?

For Example:

I can get the height of UIImageView(identifier:ImgView) by the top and bottom constraints and I want to let its width be (4/3 x height).

How can I do it?

I have ever tried doing it by this sentence:

ImgView.frame.width = ImgView.frame.height * 4.0 / 3.0

But it didn't work with an error said:

it can't assign to ImgView.frame.width

So, how can I achieve this?

Upvotes: 0

Views: 54

Answers (2)

GaétanZ
GaétanZ

Reputation: 4930

Use a ratio constraint. Easy peasy.

enter image description here

Upvotes: 2

Islam
Islam

Reputation: 3734

Try this:

CGRect frame = ImgView.frame;
frame.size.width = frame.size.height * 4/3;
ImgView.frame = frame;

Or a one-liner:

ImgView.frame = CGRectMake(ImgView.frame.origin.x,
                           ImgView.frame.origin.y,
                           ImgView.frame.size.height * 4/3,
                           ImgView.frame.size.height);

Upvotes: 1

Related Questions