I couldn't get the accepted answer to work; not that I think the answer is incorrect (far from it - that appears to be the Right Way), but as I was writing my first iOS app my head was spinning with subclasses already. So I decided to cheat.
Let's say the custom cell was controlled by a TableViewCell
class. I created a single pixel .png
file of the correct background colour and created a UIImageView
object in my custom cell. I used the Attributes inspector to set the default image and used 'Scale To Fill'. For a little more visual appeal, I then added the following to the User Defined Runtime Attributes in the Identity inspector:
KeyPath Type Value
layer.cornerRadius Number 4
layer.masksToBounds Boolean YES
Voilá, rounded corners on the cheap.
Positioned directly behind the UILabel, it looks the business, though it obviously won't resize with content (as the only content is its own image). Not a problem for me as the data to be displayed had to be a fixed size anyway.
On some values it was good to have a different colour, which can be set really easily:
cell.deviceDetailBackground.image = [UIImage imageNamed:@"detailBackground2.png"];
Where 'cell' is the incarnation of my custom cell in the cellForRowAtIndexPath
method, created using TableViewCell *cell;
. No data to display?
cell.deviceDetailBackground.image = nil;
I'm sure there will be a good reason why this is a daft idea, but as I'm just starting out with iOS development this was an easy fix that worked for me. Feel free to tell me why not to do it!