I’m subclassing UITableViewCell to have one image on the far left, then some text in the middle and then some text on the far right.
This UITableViewCell subclass will only have two images depending on a condition. What I’ve done before when I have used images in UITableViewCell subclass I have declared them as
static UIImage *image = nil;
and then in the +(void)initialize method I have assigned them. This is made only to have a class instances of the images and not using up resources to assign these images to every instance of UITableViewCell.
So my question is now, depending on a condition in my UIViewController that is calling the cellForRowAtIndexPath method I should show a UITableViewCell with imageA or imageB. So in pseudo-code it would look something like this
if (conditionA) {
// Set image of cell to be imageA
} else {
// Set image of cell to be imageB
}
So how do I achieve this with a subclassed UITableViewCell? I was thinking of one way would be to observe a property in the UITableViewCell and when that property would change I would set the cell image accordingly but that seems to be a little bloated for something that should be pretty easy?
The ideal way would be to set it in the init method of the UITableViewCell but then I would not be able to reuse the cells right?
You shouldn’t worry about redundant images being created for each instance. The
UIImageclass already has an inbuilt cache, and it does not create a new image instances as long as you are creating them using theimageNamed:selector.From the docs for the
imageNamed:method inUIImage,If the two images are predefined and won’t change, then you can simplify the subclasses cell’s interface. Only allow the users of this subclass to tell it which type of image should be used. You could use an
enumfor that.In the UITableViewCell’s subclass header, create the enum. Use whatever names suits your use-case.
Inside the implementation, override the generated setter as:
Inside your
cellForRowAtIndexPath:method, simply set this property depending on the condition.