【发布时间】:2014-06-13 14:59:27
【问题描述】:
我正在使用带有子视图 (ViewDrawing) 的自定义单元格 (CustomCell) 来绘制图像。后来我想画更多。细胞的高度也不同。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
float cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
[cell.imageView setFrame:CGRectMake(0, 0, cell.frame.size.width, cellHeight)];
if (indexPath.row < 10) {
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"FICDDemoImage00%ld.jpg",indexPath.row]];
} else {
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"FICDDemoImage0%ld.jpg",indexPath.row]];
}
[cell.imageView setNeedsDisplay];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 20 + indexPath.row * 2;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//rought calculation
return 20 + indexPath.row * 2;
//return UITableViewAutomaticDimension;
}
CustomCell.m(视图的类型为 ViewDrawing。它是一个类变量)
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
view = [[ViewDrawing alloc] init];
[self addSubview:view];
}
return self;
}
- (void)awakeFromNib
{
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (ViewDrawing *)viewDrawing {
return view;
}
- (void)setViewDrawing:(ViewDrawing *)viewDrawing {
view = viewDrawing;
}
而我在 ViewDrawing.m 中的绘制方法是这样的:
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillRect(context, rect);
[image drawInRect:rect];
}
问题是现在一切正常,但滚动有时不是很流畅。此外,该应用程序使用了 300mb 内存,这实在是太多了!似乎每个单元格都保存在内存中而不是释放。有人知道如何减少问题吗?
编辑:
我把drawRect改成:
- (void)drawRect:(CGRect)rect
{
// Drawing code
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.Vendor.Draw",NULL);
dispatch_async(backgroundQueue, ^{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillRect(context, rect);
[image drawInRect:rect];
});
}
我现在使用 imageWithContentsOfFile。现在它使用 50mb 我认为这还可以吗?!
【问题讨论】: