这是问题的视频:http://youtu.be/Jid0PO2HgcU
尝试在 Assets 库的 UITableView 中为 [cell imageView] 设置图像时遇到问题。
图像已加载,但在我触摸(选择)该单元格之前它不会出现在该单元格中。这是我设置单元格 imageView 的代码:
//Start loading the image using the image path
NSString *path = [occasion imagePath];
if (path != nil && [path hasPrefix:@"ass"])
{
NSLog(@"photo loaded from assets library");
//testing ALAssestLibrary
ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
ALAssetsLibraryAssetForURLResultBlock resultsBlock = ^(ALAsset *asset)
{
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
[[cell imageView] setImage:[image imageByScalingAndCroppingForSize:CGSizeMake(36.0, 42.0)]];
[image release];
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error){
NSLog(@"FAILED! due to error in domain %@ with error code %d", error.domain, error.code);
// This sample will abort since a shipping product MUST do something besides logging a
// message. A real app needs to inform the user appropriately.
abort();
};
//Convert path to an NSUrl
NSURL *url = [NSURL URLWithString:path];
// Get the asset for the asset URL to create a screen image.
[assetsLibrary assetForURL:url resultBlock:resultsBlock failureBlock:failureBlock];
// Release the assets library now that we are done with it.
[assetsLibrary release];
}
以上代码部分是:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
有什么想法吗?
最佳答案
我认为在这种情况下,您使用的是 iOS 定义的 UITableViewCell(而不是自定义的),它是您从“initWithStyle:reuseIdentifier:”获得的那些单元格之一。现在,这些单元格的内部构建方式是,如果您不立即分配一些内容,则相应的 subview 将不会添加到单元格的 contentView 层次结构中。这种行为是复杂自定义 View 的典型行为,只有当其所有 subview 的内容都已完全指定时,才能确定最终的单元格布局。 (例如,你有两个标签,比如说标签 A 和标签 B,标签 A 是多行的,你想在标签 A 的正下方添加标签 B,那么只有当你有标签 A 的内容时,你才能正确放置标签 B然后你计算它的高度。)。所以我想内置的 iOS 表格单元格以相同的方式完成, subview 层次结构是在“layoutSubviews”阶段构建的。
在您的情况下,您创建了单元格但推迟了提供图像的时间。但是此时 layoutSubviews 已经被调用并且没有任何图像相应的 imageView 甚至没有分配和添加到 contentView 层次结构中!
因此,根据我的说法,您的解决方案只是立即为您的 Assets 分配一个“占位符”(占位符当然可以是透明图像),这将保证您创建内部 UIImageView。出于与上述相同的原因,请注意图像尺寸,它应该接近预期的图像尺寸。一旦你的完成 block 被调用, ImageView 应该已经存在并且图像将出现。
当您点击单元格时出现图像的原因是该操作再次调用了 layoutSubviews。在这种情况下,整个代码可能会重新执行,因为您之前已经调用了“setImage:”,内部“image”属性已设置,contentView 层次结构将使用新图像重建。
您的问题的另一种可能的解决方案当然是使用“自定义”UITableViewCell(例如从 Nib 加载)。在这种情况下,您的所有 subview 都将被加载,并且您只需使用他的标签访问 UIImageView(阅读苹果文档以了解有关从 Nib 文件创建表格 View 单元格的有用技术的更多信息)。
关于ios - UITableView 中的单元格 imageView 在被选中之前不会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9352638/