Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a UIView?

I spent a couple of hours trying to position a UIView and eventually figured out that I needed to modify the views frame. So I added a 'setPosition' method to the UIViewController subclass like this

- (void) setPosition:(CGPoint)position
{

    CGRect newFrame = self.view.frame;
    newFrame.origin.x = position.x;
    newFrame.origin.y = position.y;
    self.view.frame = newFrame;

}

However, that seems so simple that I don't understand why UIViews don't have this method already, which makes me think this might not be the right way to do it. So that's my question...

Is this method OK or am I doing something I shouldn't be doing... for some reason?

like image 846
gargantuan Avatar asked Dec 10 '10 14:12

gargantuan


People also ask

What is Uiview frame?

Using the frame allows you to reposition and/or resize a view within its superview . Usually can be used from a superview , for example, when you create a specific subview.


2 Answers

Copying, Modifying and setting the frame again like you have done here is how this is generally done. This can also be done by creating a rect and setting it directly:

UIView.frame = CGRectMake(50,50,50,50);//x,y,w,h

Doing this in an animation block will animate these changes.

Alternitively you can set a views Center point with :

UIView.center = CGPointMake(50,50);

like image 142
Luke Mcneice Avatar answered Oct 21 '22 10:10

Luke Mcneice


Other way:

CGPoint position = CGPointMake(100,30);
[self setFrame:(CGRect){.origin = position,.size = self.frame.size}];

This i save size parameters and change origin only.

like image 33
Bimawa Avatar answered Oct 21 '22 10:10

Bimawa