FrameUtils – Objective-C Frame Utilities

Objective-C software developers often find themselves manipulating IOS or OSX UIView frames in various ways. Frames are resized, moved, centered, and endlessly debug printed.

My buddy, Adam, and I became really annoyed at writing code like this over and over and over and ..

  1. //move the frame left by 5 pixels
  2. view.frame = CGRectMake(view.frame.origin.x 5, view.frame.origin.y, view.frame.size.width, view.frame.size.height);

In the example given, it’s highly annoying to have a long line of code that says “view.frame.x.y.z” four different times when all we’re trying to say is “just change the frame’s position by 5 pixels”. Unfortunately, a CGRect’s inner properties are not modifiable, so developers are often resigned to code like that shown above. Fortunately, Adam and I decided to do something about the insanity of code verbosity for simple frame operations…

We created FrameUtils. FrameUtils is a collection of utility methods that simplify frame resize, movement, and debugging operations.

Consider the following examples:

  1.  #move a frame left by 50 pixels
  2.  CGRect movedFrame = [FrameUtils frame:oldFrame moveByXDelta:-50];
  4.  #resize a frame to 50×100
  5.  CGRect resizedFrame = [FrameUtils frame:oldFrame resizeToWidth:50 height:100];
  7.  #resize a frame to be 75 pixels wider
  8.  CGRect resizedFrame = [FrameUtils frame:oldFrame resizeByWidthDelta:75];
  10.  #center a frame inside another frame
  11.  CGRect centeredFrame = [FrameUtils frame:oldFrame centerInFrame:parentFrame];
  13.  #print a frame to NSLog
  14.  [FrameUtils printFrame:oldFrame];

We’ve also created a UIView category that makes these operations even simpler if you have a view in hand:

  1.  #move a UIView's frame to position 0,0
  2.  [view frameMoveToX:0 y:0];
  4.  #resize a UIView's frame to 50×100
  5.  [view frameResizeToWidth:50 height:100];
  7.  #center a UIView's frame inside another view's frame
  8.  [view frameCenterInFrame:otherView.frame];
  10.  #print a UIView's frame to NSLog
  11.  [view framePrint];

There are a number of other simple operations available in the FrameUtils utility class and the UIView+FrameUtils category.

FrameUtils, like other code on Coder Cowboy, is open source free-to-use software. Download and include it in your own project.