views:

361

answers:

4

Hello,

I'm currenly learning Obj-C and try to find the easiest way to set a position of an control.

So this works to set the object +100px:

[panel setFrame:CGRectMake(
panel.frame.origin.x, panel.frame.origin.y + 100,
panel.bounds.size.width, panel.bounds.size.height)
];

But of course this is painful.

Unfortunately this doesn't work:

panel.frame.origin.y += 100; // Compiler error

[panel setPosY:100]; // has no effect of my control

Isn't there a easy way to set the position?

Many thanks for your help!
Jürgen

+3  A: 

you can always use the center property of an object:

panel.center = CGPointMake(panel.center.x, panel.center.y + 100);

That's probably the simplest way to do this.

Ben Gottlieb
Agreed, better than mine :-)
racha
Oh, thanks to you both, I was confused about the name "center"But why isn't this directly way allowed in Obj-C?panel.center.y += 100;
This is the trick with properties; panel.center is actually a method call that returns a CGRect structure; it's not giving you direct access to the object's frame instance variable. Therefore, when you modify that struct, the original structure (inside the object's memory space) is unchanged.
Ben Gottlieb
A: 

This should work and is slightly shorter than your initial code:

CGRect frame = panel.frame;
frame.origin.y += 100;
panel.frame = frame;

Still not very pretty, though.

racha
A: 

In case you want to move it out of the way and decrease the length (so it ends at the same place) you may want to try the following (thanks racha for the idea)

    // Make space at start of label
    CGRect frame = mainLabel.frame;
    frame.origin.x += 100;
    frame.size.width -= 100;
    mainLabel.frame = frame;
Marius
A: 

The most elegant way I know of is:

panel.frame = CGRectOffset(panel.frame, 0.0f, 100.0f);
Chris Gummer