Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGRectMake(currentobject.frame.origin.x, currentObject.fram.. quicker way?

Quite often, I'll want to move an object along by 2 points, so I'll put:

CGRectMake(currentobject.frame.origin.x+2, currentObject.frame.origin.y, currentObject.frame.size.width, currentObject.frame.size.height);

Is there a quicker way, where either I can just change the 1 thing, or where I can quickly reference the current values?

like image 960
Andrew Avatar asked Aug 15 '26 12:08

Andrew


2 Answers

You should use CGRectOffset():

NSAssert(currentObject, @"%s: Must have |currentObject|.", __func__);
CGRect offsetFrame = CGRectOffset([currentObject frame], 2/*dx*/, 0/*dy*/);
[currentObject setFrame:offsetFrame];

Note the assertion: a method with a struct return value is one of the few cases where sending a message to nil can return junk rather than some equivalent to zero (0, 0.0, nil, Nil, &c.).

The equivalent of CGRectOffset() for growing or shrinking the frame (changing the size) is CGRectInset().

An alternative to using CGRectOffset() when working with UIView is to just displace the view's center:

view.center.x += 2;

This updates the frame accordingly.

like image 115
Jeremy W. Sherman Avatar answered Aug 17 '26 03:08

Jeremy W. Sherman


Either

CGRect frame = currentObject.frame;
frame.origin.x += 2;
currentObject.frame = frame;

or

CGRect frame = (CGRect){ currentobject.frame.origin.x + 2, currentObject.frame.origin.y, currentObject.frame.size };
like image 20
bddckr Avatar answered Aug 17 '26 03:08

bddckr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!