Я пытаюсь добавить видео на YouTube в мой UITableView с помощью следующего кода. Проблема, с которой я столкнулся, заключалась в том, что ячейка использовалась повторно, а веб-представления UI также использовались повторно, в результате чего в неправильных ячейках появлялись неправильные видео.
Я попытался решить эту проблему, явно удалив UIWebview из суперпредставления перед установкой видео, а также, если в ячейке отсутствует видео YouTube.
Но это кажется довольно дорогим и неэффективным. Кто-нибудь может посоветовать мне более эффективный способ сделать это так, чтобы веб-просмотр (содержащий видео) не был повторно использован в неправильных ячейках?
Фрагмент кода из "cellforRowAtIndexPath":
//Re-create a UIWebview for youtube video everytime the cell is loaded
UIWebView *thisYouTubeVideo = [[UIWebView alloc]init];
//Check if this cell contains a youtube video
if (self.youtube_url !=nil)
{
//This is the first time I explicitly remove the UIWebview from cell's contentview
for (UIView *subview in [self.contentView subviews]) {
if ([subview isKindOfClass:[UIWebView class]]) {
[subview removeFromSuperview];
}
}
//This is just to set the frame of the UIWebview
thisYouTubeVideo.frame = CGRectMake(CELL_TEXT_LEFT_MARGIN, currentYAxisValue, 240, 240);
//Key for caching
NSString *videokey=[NSString stringWithFormat:@"%@",self.answerForCell.youtube_url];
//Check if webview has been created before, just load it from the dictionary (cache)
if([self.youtubeVideoCache objectForKey:videokey]) {
thisYouTubeVideo = [[self.youtubeVideoCache objectForKey:videokey]retain];
}
else
{
//If webview does not exist in cache, load the url to webview and store in cache
NSString * videoHTML = [self embedYouTube:self.answerForCell.youtube_url frame:CGRectMake(CELL_TEXT_LEFT_MARGIN, currentYAxisValue, 240, 240)];
[thisYouTubeVideo loadHTMLString:videoHTML baseURL:nil];
[self.youtubeVideoCache setObject:thisYouTubeVideo forKey:videokey]; //Save webview in dictionary
}
//add the uiwebview to the cell's content view
[self.contentView addSubview:thisYouTubeVideo];
[thisYouTubeVideo release];
}
else
{
//If the cell DOES not contain a youtube video, do the following
thisYouTubeVideo.frame = CGRectZero;
//This is the second time I am explicitly removing the webview from cell's content view
for (UIView *subview in [self.contentView subviews]) {
if ([subview isKindOfClass:[UIWebView class]]) {
[subview removeFromSuperview];
}
}
}