views:

57

answers:

3

Hi I have a UITextField and I wnat to center this field on the center of teh view any ideas

usernameField = [[UITextField alloc] initWithFrame:CGRectMake(0, 200, 200, 28)];

instead of CGRectMake(some numbers) - I wnat to place it in the center of teh view

Thanks

+1  A: 
userNameField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 28)];
userNameField.center = CGPointMake(CGRectGetWidth(someView.bounds)/2.0f, CGRectGetHeight(someView.bounds)/2.0f);

Where someView is the superview of userNameField.

Joshua Weinberg
That's a little convoluted but it works. Using the center is much clearer code.
Roger Nolan
As I said above, center will not work for the general case.
Joshua Weinberg
+1  A: 

Why not use the view's center property?

userNameField.center = parentViewField.center;
Roger Nolan
This assumes parentView is fullScreen. Center is in frame space, not bounds space.
Joshua Weinberg
No it doesn't. It centers the subview in the parent view - which is what the question asks.
Roger Nolan
"The center is specified within the coordinate system of its superview and is measured in points." If you have 3 views deep, and your'e trying to center the 3rd view in the 2nd view. Your method will center it in the first.
Joshua Weinberg
A: 

You can directly assign it the center of the desired view:

usernameField = [[UITextField alloc] initWithFrame:CGRectMake(0, 200, 200, 28)];
usernameField.center = myView.center;
pablasso