我需要在表格单元格中绘制图像。到目前为止,在创建 View 并将其分配给单元格后,我无法正确引用 UIImageView。例如,相同的过程适用于 UILabel。
我不知道我做错了什么。
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UIImageView *imageView;
UILabel *title;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
// Setup title
title = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)] autorelease];
title.tag = 1;
[cell.contentView addSubview:title];
// Setup image
UIImageView* imageView = [[[ UIImageView alloc] initWithFrame:
CGRectMake(50, 0, 50, 50)] autorelease];
imageView.tag = 2;
[cell.contentView addSubview:imageView];
} else {
// Get references to cell views
title = (UILabel *)[cell.contentView viewWithTag:1];
imageView = (UIImageView *)[cell.contentView viewWithTag:2];
}
NSLog(@"%@", [title class]); // UILabel
NSLog(@"%@", [imageView class]); // CRASH! EXC_BAD_ACCESS
return cell;
}
最佳答案
问题是 imageView
变量的范围。如果该单元格尚不存在,您可以创建一个仅存在于 if block 中的新 UIImageView
。它隐藏了您之前声明的变量,并在 if block 结束后消失。
而不是
UIImageView *imageView = ...
你应该简单地写
imageView = ...
否则,您将创建一个与您在方法顶部声明的对象无关的新对象,并且原始 imageView
仍未定义。
关于objective-c - 尝试通过 viewWithTag 获取 UIImageView 引用后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5983346/