UIView resize evenly

95 Views Asked by At

I have a uiview subclass that i want to expand evenly. I mean I want the origin point of the view to be in the center, and have the width and height expand the same amount. Right now the origin point is in the top left, (0,0), and it expands down to the right. How would I go about doing this?

2

There are 2 best solutions below

0
On

When you change the width and height of the frame, also change the x and y position of the frame by half those amounts.

For example, if your frame is currently (40, 60, 100, 200) and you want it to be wider by 20 and higher by 30, make it (30, 45, 120, 230).

0
On

I suggest, if I understand you problem that you get the size of the superview in which the view is located. Let this view be view. Then, let your view be myView.

So all you have to do is the following :

Take half of the size of the screen for width and height values, and to position the origin of your view.

UIView view = myView.superview;
if (nil != view) {
    // Make sure your view won't extend by itself with this
    myView.autoresizingMask = UIViewAutoresizingNone;

    // Get The size of the parent view
    CGSize size = view.bounds.size;

    // Set the new frame of your view
    myView.frame = CGRectMake(size.width/2.0f, 
                              size.height/2.0f, 
                              size.width/2.0f,
                              size.width/2.0f);
}

And now your view is positioned correctly