我通过以下代码将youtube视频缩略图嵌入到我的UITableView Cell中。但是,每当我滚动表格时,视频缩略图将在单元格离开屏幕并返回时重新加载。
缓存缩略图的最有效方法是什么,以便它们只是第一次加载?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* PlaceholderCellIdentifier = @"PlaceholderCell";
SearchResult *searchResult = [self.searchResultArray objectAtIndex:indexPath.row];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier]autorelease];
UIWebView *videoView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 104, 104)];
videoView.tag = 1;
cell.imageView.image = [UIImage imageNamed:@"Placeholder"];
[cell.contentView addSubview:videoView];
[videoView release];
}
UIWebView *thisVideoView = (UIWebView *)[cell.contentView viewWithTag:1];
NSString *videoHTML = [self embedYouTube:searchResult.url frame:CGRectMake(0, 0, 104, 104)];
[thisVideoView loadHTMLString:videoHTML baseURL:nil];
return cell;
}
- (NSString*)embedYouTube:(NSString*)url frame:(CGRect)frame {
NSString* embedHTML = @"\
<html><head>\
<style type=\"text/css\">\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\"margin:0\">\
<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];
return html;
}
答案 0 :(得分:0)
在这种情况下,你可以(在第一次分配webView之后)将webView与searchResultArray中的对象与objc_setAssociatedObject相关联。
关键是,由于每次单元格可见时都会调用cellFoRowAtIndexPath,因此您不应该在那里初始化webview,但是在初始化它们时,您可以:
objc_setAssociatedObject([searchResultArray valueForKey:someIndex], &someKey, webView, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
然后在cellForRowAtIndexPath中执行:
if (objc_getAssociatedObject([searchResultArray valueForKey:indexPath.row, &someKey) != nil) {
UIWebView *thisVideoView = (UIWebView *)[cell.contentView viewWithTag:1];
*thisVideoView = objc_getAssociatedObject([searchResultArray valueForKey:indexPath.row, &someKey);
} else {
////empty webView or some loading indicator
}
您可以随时初始化webView。 &amp; someKey是静态字符,必须是该类的全局字符。