UITableViewCell drawInRect iOS7

Luke picture Luke · Sep 20, 2013 · Viewed 9k times · Source

Hi I am trying to draw strings in my UITableViewCell in iOS 7 with the following code

-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
CGRect playerNameRect = CGRectMake(0, kCellY, kPlayerNameSpace, kCellHeight);

NSDictionary*dictonary = [NSDictionary
                          dictionaryWithObjectsAndKeys:
                          [UIColor hmDarkGreyColor], NSForegroundColorAttributeName,
                          kFont, NSFontAttributeName,
                          nil];

[self.playerName drawInRect:playerNameRect withAttributes:dictonary];

}

However I can not get anything to appear... self.playerName is not nil, and the playerNameRect is correct.

I was previously using the following code to do the same thing but was recently deprecated in iOS 7

        [self.playerName drawInRect:playerNameRect withFont:kFont lineBreakMode:NSLineBreakByTruncatingTail alignment:NSTextAlignmentCenter];

What is also strange is I can not get anything to draw in drawRect on a UITableViewCell... The deprecated code works when I am drawingRect on just a UIView.

Answer

LuisCien picture LuisCien · Sep 20, 2013

You shouldn't use UITableViewCell's drawRect method to perform custom drawing. The proper way to do it is to create a custom UIView and add it as a subview of your cell (as a subview of the contentView property). You can add the drawing code to this custom view and everything will work fine.

Hope this helps!

Check out these posts too:

Table View Cell custom drawing 1

Table View Cell custom drawing 2

Table View Cell custom drawing 3