R – Subclassing UIView or composing with UIView

interface-builderiphoneobjective cuiview

I'll start by saying what I want to do because I'm unsure if I'm asking the right question. I'm making a grid based map and am going to hold an array of objects to keep the state and presentation of the map. Each object will be of a Tile class. Should I be subclassing UIView or sublass NSObject and have an ivar of UIView. I was also planning to have a UIImageView inside the UIView to load the image that represents that bit of the map. Lastly, I wanted to load the view from a NIB.

Individually I know how to do each of these things but unsure of the best practice. Any thoughts?

Best Answer

Have you considered Core Animation layers? You can create a single view with a grid of layers each with their own bounds and position within the view. It sounds like it might give you what you need. On the phone, setting a layer's contents with an image is as simple as this:

CALayer *gridLayer = [CALayer layer];
[gridLayer setContents:(id)[gridImage CGImage]];
[gridLayer setBounds:[gridImage bounds]];

// Position the layer's center a x:25.0 y:25.0 within the view
[gridLayer setPosition:CGPointMake(25.0f, 25.0f)];

[[view layer] addSublayer:gridLayer];

The variable gridImage is a UIImage* you've allocated somewhere. You would just need to calculate your layer rects and positions and place them accordingly.