views:

60

answers:

2

I'm trying to create a button programmatically and cannot change the origin. Here's the code:

UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
newButton.frame = CGRectMake(100, 200, 150, 50);
[newButton setTitle:@"Hi There" forState:UIControlStateNormal];
[self.view addSubview:newButton];

The button shows up, but centered on the screen rather than the origin I specified. If I run an NSLog to show the frame numbers, I get 0, 0, 150, 50. Changing the size numbers works, but not the origin numbers.

I've also tried copying the frame, changing the origin, then putting the new frame on inside an animation block (just to see if I could modify the origin). The animation block worked in that I could change other items (like alpha), but nothing with the frame.

What am I missing?

+1  A: 

I'm not sure why you are seeing that behaviour, but try setting the center property instead and see what happens. It may yield some insight.

Also, try setting the property after creating and displaying the button, to see if it's a order-of-operations thing.

Marcelo Cantos
Yeah, setting the center works. Just strange since all the code samples I can find suggest setting the origin should work as well. Changing the size part of the frame works (stretches the button) but not the origin. Sigh. But thanks, good suggestion.
Ryan Garcia
A: 

All I can think of is that the view which is receiving the subView is centered and the same size as your button.

Christopher Farnell
Definitely a different size--I even tried a blank project with just that code and it's doing the same thing. But Marcelo's suggestion works. Weird.
Ryan Garcia