【问题标题】:Setting UITableViewCell custom png background设置UITableViewCell自定义png背景
【发布时间】:2011-08-22 09:31:31
【问题描述】:
我正在像这样更改 UITableViewCellStyleSubtitle 的背景:
- (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;
}
我想知道是否有更好的方法可以在不使用这么多 alloc 和 autorelease 的情况下做到这一点?
我的观点是优化这些 uitableview 中的内存!
感谢您的帮助!
克洛德
【问题讨论】:
标签:
iphone
memory
uitableview
memory-management
【解决方案1】:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[...]
UIImageView *bgImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgCellNormal.png"]];
cell.backgroundView = bgImage;
bgImage release];
[...]
return cell;
}
【解决方案2】:
您可以使用nib文件通过继承UITableView Cell类来设置单元格的背景图片。
否则,您可以通过
删除自动释放的对象
UIImageView *imageView = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgCellNormal.png"];
cell. backgroundView = imageView;
[imageView release];
【解决方案3】:
如果您使用reuseIdentifier 来重用单元格,那么您实际上不会分配内存这么多次。
另外,如果你的 png 文件被添加到你的项目中,那么你可以调用 [UIImage imageNamed:@"bgCellNormal.png" 来代替。
UIImage imageNamed 函数缓存图像以提供优化。
【解决方案4】:
您不应从tableView:cellForRowAtIndexPath: 访问或设置backgroundView 属性。框架可能还没有实例化它,它可能会在你的脚下取代它。在这方面,分组表视图和普通表视图的行为不同,未来的任何新样式也可能如此。
应在tableView:willDisplayCell:forRowAtIndexPath: 中设置和/自定义背景视图。在第一次显示调用之前调用此方法。如果您愿意,可以使用它来完全替换背景。我通常会这样做:
-(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];
}