Quick-Tip: Dividing a CGRect Using CGRectDivide (Objective-C)

Torrey Betts / Tuesday, May 28, 2013


When developing iOS applications without using Interface Builder, you'll always end up with a headache of trying to work out some math to split up and layout your views. One obscure method that helps a ton when working with CGRects is CGRectDivide.

  • void CGRectDivide (CGRect rect, CGRect *slice, CGRect *remainder, CGFloat amount, CGRectEdge edge);

The CGRectDivide method splits a CGRect into two CGRects based on the CGRectEdgeand distance from the rectangle side amount provided to the method.


Dividing a CGRect

Imagine you're layout an iPad screen and want two panels that are side by side. The left half taking up roughly 30% and serving the purpose of containing selectable elements. The right half taking the remainder of the space for content that requires more viewing space. Since the smaller view will be on the left side the CGRectEdge you'll use is the CGRectMinXEdge. You could use the CGRectMaxXEdge, but would need to adjust the amount parameter in the CGRectDividemethod call.

With the general idea in place, we can construct our method call as shown below.

CGRect areaOne, areaTwo;
CGRectDivide(self.view.bounds, &areaOne, &areaTwo, self.view.bounds.size.width * 0.30, CGRectMinXEdge);

The illustration at the bottom of this section shows the two areas after they have been used to create views. To create each of the views, here is the necessary code.

View for Area One

UIView *viewOne = [[UIView alloc] initWithFrame:CGRectInset(areaOne, 10, 10)];
viewOne.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleRightMargin;
viewOne.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
viewOne.layer.borderWidth = 2.0;
viewOne.layer.borderColor = [UIColor lightGrayColor].CGColor;
viewOne.layer.shadowOffset = CGSizeZero;
viewOne.layer.shadowOpacity = 0.5;
[self.view addSubview:viewOne];

View for Area Two

UIView *viewTwo = [[UIView alloc] initWithFrame:CGRectInset(areaTwo, 10, 10)];
viewTwo.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin;
viewTwo.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
viewTwo.layer.borderWidth = 2.0;
viewTwo.layer.borderColor = [UIColor lightGrayColor].CGColor;
viewTwo.layer.shadowOffset = CGSizeZero;
viewTwo.layer.shadowOpacity = 0.5;
[self.view addSubview:viewTwo];

The layout was easily created without any math that confuses code readability and with each view now setup the child content can be added.

Dividing a CGRect

Download the Example Project

The Xcode project source code for this quick tip can be downloaded by clicking this link.