Deriving from UIView

The "Hello, Window!" example showed the very minimal code needed to construct and display a window/view pair. Because the UIView class itself is merely a base class, it didn't actually display anything. To create a useful application, a new class can be derived from UIView, allowing its methods to be overridden to add functionality. This controlling view can then display other objects, such as text boxes, images, etc.

To derive a subclass from UIView, write a new interface and implementation declaring the subclass. The following snippet creates a subclass named MainView:

@interface MainView : UIView
{

}

- (id)initWithFrame:(CGRect)rect;
- (void)dealloc;
@end

At the very least, two UIView class methods should be overridden. The initWithFrame method is called when the view is first instantiated and is used to initialize the view class. A display region is passed in to define its coordinates (offset to its parent) and size it should display as. Any code that initializes variables or other objects can go into this method. The second method, dealloc, is called when the UIView object is disposed of. Any resources previously allocated within your class should be released here.

These two methods are the basis for all other activity within the view class. Here are the templates for them:

@implementation MainView - (id)initWithFrame:(CGRect)rect { if ((self == [ super initWithFrame: rect ]) != nil) { /* Initialize member variables here */ /* Allocate initial resources here ...

Get iPhone Open Application Development 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.