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 ..
-
//move the frame left by 5 pixels
-
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:
-
#move a frame left by 50 pixels
-
CGRect movedFrame = [FrameUtils frame:oldFrame moveByXDelta:-50];
-
-
#resize a frame to 50×100
-
CGRect resizedFrame = [FrameUtils frame:oldFrame resizeToWidth:50 height:100];
-
-
#resize a frame to be 75 pixels wider
-
CGRect resizedFrame = [FrameUtils frame:oldFrame resizeByWidthDelta:75];
-
-
#center a frame inside another frame
-
CGRect centeredFrame = [FrameUtils frame:oldFrame centerInFrame:parentFrame];
-
-
#print a frame to NSLog
-
[FrameUtils printFrame:oldFrame];
We’ve also created a UIView category that makes these operations even simpler if you have a view in hand:
-
#move a UIView's frame to position 0,0
-
[view frameMoveToX:0 y:0];
-
-
#resize a UIView's frame to 50×100
-
[view frameResizeToWidth:50 height:100];
-
-
#center a UIView's frame inside another view's frame
-
[view frameCenterInFrame:otherView.frame];
-
-
#print a UIView's frame to NSLog
-
[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.