The most flexible way to draw a UIView is to draw it yourself. Actually, you don’t draw a UIView; you subclass UIView and endow the subclass with the ability to draw itself. When a UIView needs drawing, its
drawRect: method is called. Overriding that method is your chance to draw. At the time that
drawRect: is called, the current graphics context has already been set to the view. You can use Core Graphics functions or UIKit convenience methods to draw into that context.
You should never call
drawRect: yourself. If a view needs updating and you want its
drawRect: called, send the view the
setNeedsDisplay message. This will cause
drawRect: to be called at the next proper moment.
If you subclass a built-in UIView subclass, don’t override
drawRect: unless you are assured that this is legal. For example, it is not legal to override
drawRect: in a subclass of UIImageView; you cannot combine your drawing with that of the UIImageView.
So let’s begin again. We’ll have a UIView subclass called MyView, in which we’ll do all our drawing. How this class gets instantiated, and how the instance gets into our view hierarchy, isn’t important. Here, I’ll do it in code as the app launches:
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 release];
The only really new thing here is that we set our UIView instance’s
opaque property to NO. If we don’t ...