Content Mode

A view that draws something within itself, as opposed to merely having a background color and subviews (as in the previous chapter), has content. This means that its contentMode property becomes important whenever the view is resized. As I mentioned earlier, the drawing system will avoid asking a view to redraw itself from scratch if possible; instead, it will use the cached result of the previous drawing operation. So, if the view is resized, the system may simply stretch or shrink or reposition the cached drawing, if your contentMode setting instructs it to do so.

It’s a little tricky to illustrate this point, because I have to arrange for the view to be resized without also causing it to be redrawn (that is, without triggering a call to drawRect:). Here’s how I’ll do that. As the app starts up, I’ll create the MyView instance in code and put it in the window, much as before. Then I’ll use delayed performance to resize the MyView instance after the window has shown and the interface has been initially displayed:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { MyView* mv = [[MyView alloc] initWithFrame: CGRectMake(0, 0, self.window.bounds.size.width - 50, 150)]; mv.center = self.window.center; [self.window addSubview: mv]; mv.opaque = NO; mv.tag = 111; // so I can get a reference to this view later [mv release]; [self.window makeKeyAndVisible]; [self performSelector:@selector(resize:) withObject:nil afterDelay:0.1]; ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.