CGRect utils an helper for UIView frame

To move a UIView by 10 pixel I have been writing this kind of code in Objective-C

myView.frame = CGRectMake(myView.frame.origin.x + 10,
                         myView.frame.origin.y,
                         myView.frame.size.width,
                         myView.frame.size.height);

From now I will simply write:

myView.x += 10;


Using category and @property

or

CGRectAddXToView(myView, 10);

Using macro

CGRect Utils source code available on github.

Using category and @property

We need to create a category in order to dynamically add a property to the UIView class.
By creating a property using “@property(retain, nonatomic) x;” we implicitly create getter and setter to the class:
- (CGFloat)x; //getter
- (void)setX:(CGFloat)x //setter

Let’s overwrite them to implement the correct behaviour.

UIView+CGRectUtils.h

@interface UIView (CGRectUtils)

@property (nonatomic) CGFloat x;

@end

UIView+CGRectUtils.m

@implementation UIView (CGRectUtils)
- (CGFloat)x {
    return self.frame.origin.x;
}

- (void)setX:(CGFloat)x {
    self.frame = CGRectMake(x, self.frame.origin.y,
                            self.frame.size.width, self.frame.size.height);
}
@end

As we are dynamically adding functions to the UIView class. Remember, “self” is our UIView.

Using macro

Macro as piece of code who will be search and replace just before the compiler start his job.
It can be handy to use them as “shortcut”

#define CGRectAddXToView( v, addX ) \
v.frame = CGRectMake( v.frame.origin.x+addX, \
                      v.frame.origin.y, \
                      v.frame.size.width, \
                      v.frame.size.height )

As macro are precompiled instruction those two lines of code will be compile the exact same way:

CGRectAddXToView(myView, 10); // this line is...
myView.frame = CGRectMake( v.frame.origin.x+addX, //...the same as this one
                           v.frame.origin.y,
                           v.frame.size.width,
                           v.frame.size.height );

Conclusion

CGRect Utils is able to do more. It manipulating the x, y, width and heigh on UIView. But can also be use to work with pure CGRect.
Check CGRect Utils source code on github.