Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting UITableViewCell custom png background

I am changing the background of an UITableViewCellStyleSubtitle like this :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [...]
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"bgCellNormal" ofType:@"png"];
    cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:imagePath]] autorelease];
    [...]
    return cell;
}

I am wondering if there is a better way to do this without using so many alloc and autorelease ? My point is to optimise memory in these uitableview !

Thanks for your help !

Kheraud

like image 873
kheraud Avatar asked Jan 30 '26 23:01

kheraud


2 Answers

You should not access, or set, the backgroundView property from tableView:cellForRowAtIndexPath:. The framework may not have instantiated it yet, and it may replace it under your feet. Grouped and plain table views behave differently in this regard, and so may any new future style.

The background view should be set&/customized in tableView:willDisplayCell:forRowAtIndexPath:. This method is called just before the call is to be displayed the first time. You can use it to completely replace the background if you like. I useually do something like this:

-(void)  tableView:(UITableView*)tableView 
   willDisplayCell:(UITableViewCell*)cell 
 forRowAtIndexPath:(NSIndexPath*)indexPath;
{
    static UIImage* bgImage = nil;
    if (bgImage == nil) {
        bgImage = [[UIImage imageNamed:@"myimage.png"] retain];
    }
    cell.backgroundView = [[[UIImageView alloc] initWithImage:bgImage] autorelease];
}
like image 52
PeyloW Avatar answered Feb 01 '26 11:02

PeyloW


If you're using reuseIdentifier for reusing the cell then you won't really be allocating memory so many times.

Also, if your png file is added to your project then you can call [UIImage imageNamed:@"bgCellNormal.png" instead.

UIImage imageNamed function caches the image to provide optimization.

like image 36
Gary Avatar answered Feb 01 '26 13:02

Gary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!