开发者

Setting UITableViewCell custom png background

开发者 https://www.devze.com 2023-03-05 06:38 出处:网络
开发者_如何学运维I am changing the background of an UITableViewCellStyleSubtitle like this : - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
开发者_如何学运维

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


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];
}


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.


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [...]
    UIImageView *bgImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgCellNormal.png"]];
    cell.backgroundView = bgImage;
     bgImage release];
    [...]
    return cell;
}


you can use the nib file to set the background image of the cell by inheriting UITableView Cell class.

OtherWise you can remove the autoreleased object by

 UIImageView *imageView = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgCellNormal.png"];
 cell. backgroundView = imageView;
 [imageView release];
0

精彩评论

暂无评论...
验证码 换一张
取 消