Archive for the 'cocoa' category
iphone: drawing rectangles
April 28, 2009 9:33 amMac/AppKit and iPhone/UIKit development are more alike than different. In general, I’d say the iPhone APIs feel more “fresh” than their Mac equivalents. It seems to me like the current crop of Cocoa engineers at Apple have learned a lot in the years since the company ditched “classic” MacOS for an updated version of NextStep, and they’ve used that wisdom to design this new crop of frameworks. And they’re not afraid to revisit past decisions that didn’t work out so well: they discarded MacOSX’s view-origin-in-the-lower-left-corner mistake and put it in the upper left corner for the iPhone, where it belongs.
On the other hand, AppKit is far more complete than UIKit. Almost anything user-interface-related you might want to do on the Mac is covered by APIs in AppKit. UIKit is missing many of those amenities, likely because it is targeted at resource-constrained devices that don’t have the space for dozens of multi-megabyte frameworks. The practical upshot is that I’ve spent a lot of time writing iPhone stuff that AppKit would have provided for me. All the more reason to write blog posts like this one, so coders can google up the answers rather than spending days reinventing wheels.
I like drawing rectangles. Only rarely do they end up in my final apps, but I use them a lot while debugging, to ensure that a view area I’ve staked out is where it should be. On the iPhone, this kind of thing is done with Core Graphics. It is a very complete framework. You can do anything with it. The down side is that CG code tends to be verbose and complicated, requiring lots of function calls to do the simplest things. This is a situation crying out for wrapper functions.
I’ve written a UIView category that provides methods for drawing just about any type of rectangle you can think of: filled or outlined, rounded corners or square, including point-drawing methods. You can provide a color to draw with, or use the current draw color, which is black, unless you change it. You can draw a translucent rectangle by specifying a draw color that has an alpha value of less than one. You can change the radius of the rounded corners drawn by fiddling with the constant kCornerSize at the top of the implementation file.
This is beginner-level stuff, so I guess I should add that UIKit doesn’t let you draw things whenever you feel like it. (That’s true for all GUI environments I’ve ever programmed for, now that I think about it.) You must draw only within a UIView’s drawRect: method. If this is news to you, you should read one of Apple’s introductory texts before continuing.
Here’s a sample drawRect: method you can add to an existing view to demonstrate the rect-drawing methods:
-(void)drawRect:(CGRect)rect { CGRect test = CGRectMake(0.0, 0.0, 20.0, 20.0); [self strokeRect:test color:[UIColor magentaColor]]; test.origin.x += test.size.width; [self strokeRoundRect:test color:[UIColor yellowColor]]; test.origin.x += test.size.width; [self fillRect:test color:[UIColor blueColor]]; test.origin.x += test.size.width; [self fillRoundRect:test color:[UIColor redColor]]; }
… which produces the output shown in the screen-shot. here’s the header file for the category:
// WBViewRect.h -- rectangle drawing methods for UIView // by allen brunson march 2 2009 #ifndef WBVIEWRECT_H #define WBVIEWRECT_H #import <UIKit/UIKit.h> @interface UIView (WBViewRect) // save and restore graphics context -(void)contextRestore:(CGContextRef)context; -(CGContextRef)contextSave; // points -(void)drawPoint:(CGPoint)point; -(void)drawPoint:(CGPoint)point color:(UIColor*)color; // filled rects -(void)fillRect:(CGRect)rect; -(void)fillRect:(CGRect)rect color:(UIColor*)color; // filled rects with rounded corners -(void)fillRoundRect:(CGRect)rect; -(void)fillRoundRect:(CGRect)rect color:(UIColor*)color; // outlined rects -(void)strokeRect:(CGRect)rect; -(void)strokeRect:(CGRect)rect color:(UIColor*)color; // outlined rects with rounded corners -(void)strokeRoundRect:(CGRect)rect; -(void)strokeRoundRect:(CGRect)rect color:(UIColor*)color; @end #endif // WBVIEWRECT_H
Finally, here’s the implementation file:
// WBViewRect.mm -- rectangle drawing methods for UIView // by allen brunson march 2 2009 #include "WBViewRect.h" #pragma mark module data static const CGFloat kCornerSize = 5.0; static CGRect rectStrokeAdjust(CGRect rect) { rect = CGRectIntegral(rect); rect.origin.x += 0.5; rect.origin.y += 0.5; rect.size.width -= 1.0; rect.size.height -= 1.0; return rect; } static void roundRect(CGContextRef context, CGRect rect, CGFloat ovalWidth, CGFloat ovalHeight) { CGFloat fw = 0.0; CGFloat fh = 0.0; assert(ovalWidth >= 1.0); assert(ovalHeight >= 1.0); CGContextSaveGState(context); CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect)); CGContextScaleCTM(context, ovalWidth, ovalHeight); fw = rect.size.width / ovalWidth; fh = rect.size.height / ovalHeight; CGContextMoveToPoint(context, fw, fh / 2.0); CGContextAddArcToPoint(context, fw, fh, fw / 2.0, fh, 1.0); CGContextAddArcToPoint(context, 0.0, fh, 0, fh / 2.0, 1.0); CGContextAddArcToPoint(context, 0.0, 0.0, fw / 2.0, 0, 1.0); CGContextAddArcToPoint(context, fw, 0.0, fw, fh / 2.0, 1.0); CGContextClosePath(context); CGContextRestoreGState(context); } @implementation UIView (WBRectView) -(void)contextRestore:(CGContextRef)context { CGContextRestoreGState(context); } -(CGContextRef)contextSave { CGContextRef ctxt = UIGraphicsGetCurrentContext(); CGContextSaveGState(ctxt); return ctxt; } -(void)drawPoint:(CGPoint)point { [self drawPoint:point color:nil]; } -(void)drawPoint:(CGPoint)point color:(UIColor*)color { CGRect rect = CGRectMake(point.x, point.y, 1.0, 1.0); [self fillRect:rect color:color]; } -(void)fillRect:(CGRect)rect { [self fillRect:rect color:nil]; } -(void)fillRect:(CGRect)rect color:(UIColor*)color { CGContextRef ctxt = [self contextSave]; if (color) { CGContextSetFillColorWithColor(ctxt, [color CGColor]); } UIRectFill(rect); [self contextRestore:ctxt]; } -(void)fillRoundRect:(CGRect)rect { [self fillRoundRect:rect color:nil]; } -(void)fillRoundRect:(CGRect)rect color:(UIColor*)color { CGContextRef ctxt = [self contextSave]; roundRect(ctxt, rect, kCornerSize, kCornerSize); if (color) { CGContextSetFillColorWithColor(ctxt, [color CGColor]); } CGContextFillPath(ctxt); [self contextRestore:ctxt]; } -(void)strokeRect:(CGRect)rect { [self strokeRect:rect color:nil]; } -(void)strokeRect:(CGRect)rect color:(UIColor*)color { CGContextRef ctxt = [self contextSave]; if (color) { CGContextSetStrokeColorWithColor(ctxt, [color CGColor]); } UIRectFrame(rect); [self contextRestore:ctxt]; } -(void)strokeRoundRect:(CGRect)rect { [self strokeRoundRect:rect color:nil]; } -(void)strokeRoundRect:(CGRect)rect color:(UIColor*)color { CGContextRef ctxt = [self contextSave]; rect = rectStrokeAdjust(rect); roundRect(ctxt, rect, kCornerSize, kCornerSize); if (color) { CGContextSetStrokeColorWithColor(ctxt, [color CGColor]); } CGContextStrokePath(ctxt); [self contextRestore:ctxt]; } @end
Categories: cocoa, iphone, objective-c, programming
Comments Off
iPhone: UITextField and the virtual keyboard, part II
April 20, 2009 8:42 pmI’ve written about this subject before, but I didn’t do a very good job. Many weeks of intensive iPhone programming later, I am ready to deliver my definitive treatise on this subject.
The Problem
Say you’ve got a UITextField that you want the user to type something into. It’s located near the bottom of the screen. The user touches the control to begin editing. The virtual keyboard pops up, which completely covers the UITextField. It is now impossible for the user to see what she’s typing. You have to write your own custom code to move the text field out of the way before the keyboard pops up, so the user can see it.
This is against the spirit of Cocoa. AppKit on the Mac and UIKit on the iPhone normally give you decent behavior by default, and lots of hooks you can use for customization, if the defaults don’t suit your situation. In this case, they gave us a big problem by default and very little guidance towards solving it. Apple’s own example code does not do a good job with this. What we’re left with is lots of blog authors like me writing half-baked solutions to partial subsets of the problem, whereas Apple could have solved all of it, easily. Disappointing.

keyboardscroll screen-shot
Having lived with this for awhile, I thought about how best to write something definitive, so I don’t have to keep tripping over this issue again and again. The solutions I’ve seen on programming forums and blogs involve code snippets you can drop into an existing view controller, but you have to do so every time you write a new view that contains text fields. The height of cut-and-paste code reuse.
My first idea was to add a category to UIViewController. Then every new view controller I write from now on would get textfield-handling ability “for free.” But Apple has already solved this problem for the UITableView object with special code inside UITableViewController, as of iPhone OS version 2.2. It’s not right to apply my fix to every view controller if some don’t need it. So instead I implemented a descendant of UIViewController, which can be derived from to create new view controllers.
The Solution
My keyboardscroll Xcode project shows you two ways you can solve this problem. If you’re using a UITableView, the issue is solved for you by UITableViewController, if you get all the connections right. I’ve included a table view controller that works this way, because it was harder than I thought it would be. My first attempt failed miserably. If you’re using some other view type, you can write a new view controller descended from my own WBKeyboardViewController class, which the example project shows you how to do.
My view controller works for views that contain any number of UITextFields. The content view can be a UIView or UIScrollView, either works fine. Both portrait and landscape modes are fully supported.
The only serious limitation is that my code doesn’t cope with UITextViews, which the user can also type into, and are subject to the same problem. I don’t have enough experience with text views to have a good idea about how to approach that problem yet. My first guess is that my view controller could be made to deal with them fairly easily, with a few special cases here and there.
To the greatest extent possible, I’ve avoided hard-coding pixel counts. For example, the portrait mode virtual keyboard is 216 pixels tall, and the landscape one is 162 — but those two numeric constants do not appear anywhere in the code. The proper values to use are retrieved from the operating system. Apple’s own UICatalog sample project hard-codes the height of the keyboard, so I didn’t discover that there is a better way until I had been searching for articles about this for some time.
Hard-coded pixel counts are not just a theoretical concern. “In iPhone OS 1.1.4 and earlier, the keyboard height in landscape orientation was 180 pixels.” Straight from Apple’s own documentation. Of course, that was from before the iPhone SDK existed. I think they’d be reluctant to make such a change today, since it would break so many third-party apps. Better safe than sorry, though.
There are 40 total UITextFields in my example project spread over two views, and they always, always get out of the way before the keyboard appears. I’ve tested this code thoroughly in the simulator. I’ll be using it on a real iPhone soon, so if there are issues in that scenario, I’ll find them and update this blog post. There are no bugs that I’m aware of. If you find one, I’d love to hear about it, so I can fix it.
Landscape Mode is the Devil’s Own Handiwork
Whew, this was way more complicated than I thought it would be. Apple chose to implement the landscape modes far differently than I would have. I say “modes” rather than “mode,” because there are two of them. The iPhone’s user interface can be rotated to one of four orientations: portrait, landscape, portrait upside down, and landscape upside down.
When your view rotates into landscape mode, almost all of UIKit remains stuck in portrait mode. That means you have to write lots of special cases. Here’s the first example. This code snippet gets you the bounds rect of the iPhone’s screen:
CGRect rect = [[UIScreen mainScreen] bounds];
In portrait mode, the rect returned has a height of 480 pixels and a width of 320, which is correct. In landscape mode, the rect returned is exactly the same as the one you get in portrait mode. Erm. Okay, it’s easy enough to write a wrapper function that swaps the rect’s width and height when appropriate, which I did.
Next problem. UIView contains methods for converting rects and points from the coordinate system of one view into another, convertRect:toView: being one of them. I’ve successfully used those methods in portrait modes, but not in landscape modes. It appears to me that, while your view is in landscape mode, the main window remains in portrait mode, so translations between the two are nonsensical. I couldn’t make it work, anyway. Could be because they’re weird in the way I just described, or it could be because I don’t know what I’m doing. Either way, I had to abandon UIView’s conversion methods and roll my own.
The next problem I ran into indicates the UIKit’s designers’ intent quite strongly. UIApplication has a property called statusBarFrame. Normally I wouldn’t need to know the size of the status bar, but I was forced to roll my own coordinate conversion methods, remember. In portrait mode, the property returns a width of 320 pixels and a height of 20 pixels, which is correct. In landscape mode, it says the status bar is 20 pixels wide and 480 pixels tall! That’s obviously wrong, from the perspective of your landscape-mode view. It would be correct only from the perspective of a parent view that’s still in portrait mode. Yet another special case I had to write for the landscape modes.
It took me three days to get my view controller working right, despite the fact that it is only around 250 lines of code. Largely because I have come to trust that UIKit will Do The Right Thing in almost every case, so I could barely conceive of the idea that it would ever tell me that the status bar is 480 pixels tall with a straight face. Not at all what I was expecting, so I had to abandon a lot of early code and rethink my assumptions.
Here’s the code: keyboardscroll.zip
Categories: cocoa, iphone, objective-c, programming
Comments Off
iPhone: UIImage rotation and mirroring
March 30, 2009 2:19 amUpdate: This post has been superseded. Please go read this instead: UIImage rotation and scaling.
My access logs show that you webbernauts like my iPhone articles better than anything else on this site. Very well then, here’s another one.
I recently found myself with a need to rotate the contents of a UIImage 90 degrees to the right or left and then display it. Apparently this is easy if your image is inside a UIImageView and you’re willing to rotate the whole view, but that’s not what I have in mind. Rotating the UIImage itself turns out to be pretty danged complicated, and requires a great deal of math. I suck at math.
Fortunately for me, the code given in this guy’s blog post tackles 95 percent of the problem, and 100 percent of the math. Heh! It’s not quite what I want, however. The function given in that blog post queries the EXIF data inside the image and rotates it based on that. I want the method’s caller to be able to specify what type of rotation should be done. I tinkered with the code for awhile and got exactly what I wanted.
The original blog post’s code was written as a standalone C function. I wrote my version as a category attached to UIImage. Say you’ve got a UIImage you want to rotate 90 degrees left. It’s done like this:
newImage = [oldImage rotate:UIImageOrientationLeft];
newImage will be a newly-created copy of oldImage, rotated 90 degrees left. Other options include UIImageOrientationRight, UIImageOrientationDown (for a new image that’s an upside-down copy of the original), and so on. There are also “mirrored” variants, which both rotate the image and mirror its contents left-to-right.
In the process of getting it to work the way I wanted, I made a bunch of changes to the code. I reformatted it so that the lines are no longer than 78 characters. (One of these days I’m going to write a blog post about why I think that’s a good thing.) The original function had two or more unnecessary copies of some data and superfluous calls to external functions, which I eliminated. The old code trimmed the size of the original image if it was bigger than a certain size, which I eliminated. The original had several copies of an identical clause for swapping the width and height of a CGRect, which I refactored into a separate helper function. There are other changes as well, but I’ll spare you the details.
Okay, one more change that I’m going to document. I am 85 percent sure that the original code has a bug. It does not work properly when the input orientation is UIImageOrientationLeftMirrored or UIImageOrientationRightMirrored. The new image gets partially chopped off along one edge, which I fixed. It could be that it was not a bug in the context where the original code was being used, but it definitely is in this new context. I’ve tested all orientations in the iPhone simulator, and they all work.
First, here’s UKImage.h, which defines the category.
// UKImage.h -- extra UIImage methods // by allen brunson march 29 2009 #ifndef UKIMAGE_H #define UKIMAGE_H #import <UIKit/UIKit.h> @interface UIImage (UKImage) -(UIImage*)rotate:(UIImageOrientation)orient; @end #endif // UKIMAGE_H
Now here’s UKImage.mm, which defines the rotate: method. You can rename this file to UKImage.m if you never use any C++ constructs in your code.
// UKImage.mm -- extra UIImage methods // by allen brunson march 29 2009 // based on original code by Kevin Lohman: // http://blog.logichigh.com/2008/06/05/uiimage-fix/ #include "UKImage.h" static CGRect swapWidthAndHeight(CGRect rect) { CGFloat swap = rect.size.width; rect.size.width = rect.size.height; rect.size.height = swap; return rect; } @implementation UIImage (UKImage) -(UIImage*)rotate:(UIImageOrientation)orient { CGRect bnds = CGRectZero; UIImage* copy = nil; CGContextRef ctxt = nil; CGImageRef imag = self.CGImage; CGRect rect = CGRectZero; CGAffineTransform tran = CGAffineTransformIdentity; rect.size.width = CGImageGetWidth(imag); rect.size.height = CGImageGetHeight(imag); bnds = rect; switch (orient) { case UIImageOrientationUp: // would get you an exact copy of the original assert(false); return nil; case UIImageOrientationUpMirrored: tran = CGAffineTransformMakeTranslation(rect.size.width, 0.0); tran = CGAffineTransformScale(tran, -1.0, 1.0); break; case UIImageOrientationDown: tran = CGAffineTransformMakeTranslation(rect.size.width, rect.size.height); tran = CGAffineTransformRotate(tran, M_PI); break; case UIImageOrientationDownMirrored: tran = CGAffineTransformMakeTranslation(0.0, rect.size.height); tran = CGAffineTransformScale(tran, 1.0, -1.0); break; case UIImageOrientationLeft: bnds = swapWidthAndHeight(bnds); tran = CGAffineTransformMakeTranslation(0.0, rect.size.width); tran = CGAffineTransformRotate(tran, 3.0 * M_PI / 2.0); break; case UIImageOrientationLeftMirrored: bnds = swapWidthAndHeight(bnds); tran = CGAffineTransformMakeTranslation(rect.size.height, rect.size.width); tran = CGAffineTransformScale(tran, -1.0, 1.0); tran = CGAffineTransformRotate(tran, 3.0 * M_PI / 2.0); break; case UIImageOrientationRight: bnds = swapWidthAndHeight(bnds); tran = CGAffineTransformMakeTranslation(rect.size.height, 0.0); tran = CGAffineTransformRotate(tran, M_PI / 2.0); break; case UIImageOrientationRightMirrored: bnds = swapWidthAndHeight(bnds); tran = CGAffineTransformMakeScale(-1.0, 1.0); tran = CGAffineTransformRotate(tran, M_PI / 2.0); break; default: // orientation value supplied is invalid assert(false); return nil; } UIGraphicsBeginImageContext(bnds.size); ctxt = UIGraphicsGetCurrentContext(); switch (orient) { case UIImageOrientationLeft: case UIImageOrientationLeftMirrored: case UIImageOrientationRight: case UIImageOrientationRightMirrored: CGContextScaleCTM(ctxt, -1.0, 1.0); CGContextTranslateCTM(ctxt, -rect.size.height, 0.0); break; default: CGContextScaleCTM(ctxt, 1.0, -1.0); CGContextTranslateCTM(ctxt, 0.0, -rect.size.height); break; } CGContextConcatCTM(ctxt, tran); CGContextDrawImage(UIGraphicsGetCurrentContext(), rect, imag); copy = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return copy; } @end
Categories: cocoa, iphone, objective-c, programming
Comments Off
iphone newbie: view coords, UITextField
March 3, 2009 7:49 am
I count three people in my access logs who got here by searching for iPhone programming material, two who are trying to create nibless apps. Rock on, fellow Interface Builder haterz!
iPhone programming is typically very similar to Mac programming. One big change I’ve noticed is that they’ve moved the origin for view coordinates. For NSView on the Mac, the origin point is at the lower left corner, Y coords get bigger as you move up the window. That always seemed deeply, profoundly wrong to me. I guess I’m not the only one who feels that way, because on the iPhone, the origin point is now in the upper left corner, with Y coords getting bigger as you move down the view.
To make matters worse on the Mac, it’s possible to have an NSView with “flipped” coords. In that mode, the origin point is at the top left, as god intended. Some of the stock views are like this, I think NSTableView is one of them. Those views will go crazy if you try to set them back to the “normal” Mac way, displaying their contents incorrectly. What a mess. Looks like iPhone/UIView doesn’t have the “flipped” concept, so everything’s cool again.

Well, except for other annoyances. Today’s culprit: UITextField. This is the standard one-line text input control for the user to type into, analogous to the Mac’s NSTextField. Way, WAY more complicated than it should be. Every single thing that happens to it in its lifetime, you have to write custom code for.
Creating a UITextField and adding it to a parent view is a trial-and-error affair, sprinkled with magic pixel counts like 30.0 and 4.0 and so on. It’s not just me, that’s the way they do things in Apple’s UICatalog sample app, which shows you how to create most control types. This is bad. What if the dimensions of the control change in the next iPhone software update?
When the user touches the control, the onscreen keyboard pops up. Surprise! It will almost certainly cover the UITextField the user is typing into, so they can’t see what they’re doing. The next step is that you have to write code to scroll your view up to get out of the keyboard’s way when it appears, then scroll the view back down when the keyboard disappears. Why isn’t the iPhone OS doing this for me? Madness!
Now you must add code to your view controller’s viewWillAppear: method, to catch notifications for when the keyboard appears and disappears. Then add more code to viewWillDisappear: to disable those notifications. Then write a method that gets called when the keyboard appears or disappears, to scroll your view up or down by a magic number of pixels. UICatalog hard-codes the value 150.0, which is I suppose the height of the onscreen keyboard. That wasn’t quite right for me, I discovered I needed it to be 166.0. I’m sure that will be the right value to use always and forevermore, right Apple? Sheesh.
Finally, the keyboard won’t ever go away unless you write more code to dismiss it. You must make your view controller the text control’s delegate and write a textFieldShouldReturn: method so you can do something with the Enter key and tell the keyboard to go away. Six new methods later, your quest is at an end. Until the next time you need a UITextField.
Categories: cocoa, iphone, mac, objective-c, programming
Comments Off
nibless
February 23, 2009 7:59 pmUpdate: The linked blog post in this article that explains how to create a nibless Xcode project is now dead. Go read this post instead.
This might sound heretical, but here goes: I don’t like Interface Builder.
I used the 2.x versions to build this. I got along with it acceptably well at the time, I guess, although it was never my favorite program. Then Apple completely rewrote it from the ground up for 3.0, whenceforth it didst suck, yea verily.
My complaint is a simple one: Interface Builder is 87 billion times more complex than it should be. Dozens of windows, hundreds of tabs, thousands of buttons, sliders, text input fields, check boxes, outlets, hinges, beads, knobs, joints, pipes, and zippers. Every time I start it up, I dread the ordeal I know I’m in for. It takes me half an hour to find the one check box I need in a sea of extraneous crud. Once I get a view or window set up appropriately, the steps I went through to get there are not easily documented or remembered.
I know that laying out user interfaces and wiring up controls is a big job. I know that somebody must need all that crud I never use, or it wouldn’t be there. But couldn’t Apple use its legendary user interface skills to de-emphasize the infrequently-used parts? I’m dyin’ here.
If you’re writing a Mac/Cocoa app, I guess you’re stuck with it. You’ve probably got at least a few fairly complicated windows to manage, along with dozens of menu items. But if you’re writing an iPhone/UIKit app, the value proposition changes. iPhone apps tend to have only a handful of user interface objects and connections. In this scenario, Interface Builder’s weaknesses outweigh its strengths.
It’s easy to assume that it’s impossible to build an iPhone or Mac app without Interface Builder. As a matter of fact, I once spent several months figuring out how to build Cocoa apps without NIBs, because I was writing a cross-platform GUI framework, so obviously they had to go. It wasn’t easy, because it’s not done very often, but I succeeded. And the first version of the iPhone SDK didn’t even give you the opportunity to use Interface Builder, you were forced to create your user interface in code.
Now we reach the part of the blog entry where I should tell you how to make an iPhone app without NIBs. Alas, this gentleman has already done a far better job of it than I would have. So you can instead read what he wrote, secure in the knowledge that someone else produced a solution, while I produced a bunch of hot air and whining. You’re welcome.
I’m now working on the user interface for my first iPhone app. I have several views set up, all completely NIB-free. It’s far preferable to create a user interface element in 10 lines of code, rather than making yet another soul-destroying 20-minute slog through Interface Builder. I suppose it’s possible that I’ll run into some situation that forces me to reconsider, but at this point, I’m willing to go far, FAR out of my way to avoid having to invite that sad piece of software back into my life, thank you very much.
Categories: cocoa, iphone, mac, objective-c, programming
Comments Off

