Created
October 15, 2012 17:11
-
-
Save cstrap/3893697 to your computer and use it in GitHub Desktop.
Example of working tableview with async images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
static NSString *CellIdentifier = @"Cell"; | |
CGSize newSize = CGSizeMake(70, 70); | |
Story *currentStory = [[storyParser stories] objectAtIndex:indexPath.row]; | |
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; | |
if (cell == nil) { | |
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; | |
} | |
cell.textLabel.textColor = [UIColor whiteColor]; | |
cell.imageView.image = [UIImage imageNamed:@"tableviewDefault"]; | |
//Load images from web asynchronously with GCD | |
if(!currentStory.image){ | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ | |
if (currentStory.imageURL) { | |
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:currentStory.imageURL]]; | |
dispatch_sync(dispatch_get_main_queue(), ^{ | |
currentStory.image = [UIImage imageWithData:data]; | |
UIImage *resizedImage = [self imageWithImage:currentStory.image scaledToSize:newSize]; | |
cell.imageView.image = resizedImage; | |
[self.tableView beginUpdates]; | |
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] | |
withRowAnimation:UITableViewRowAnimationNone]; | |
[self.tableView endUpdates]; | |
}); | |
} else | |
cell.imageView.image = [UIImage imageNamed:@"tableviewDefault"]; | |
}); | |
} | |
else { | |
UIImage *resizedImage = [self imageWithImage:currentStory.image scaledToSize:newSize]; | |
cell.imageView.image = resizedImage; | |
} | |
cell.textLabel.text = [self addElipses: currentStory.title]; | |
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; | |
cell.textLabel.numberOfLines = 0; | |
return cell; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment