Reputation: 2761
Hi I have this code to download images from the server and then to show them in table view with some text (if there is no image I want to show the text anyway):
//download part
NSMutableString *photourl=[[NSMutableString alloc] initWithString:url_image];
[photourl appendString:[dic objectForKey:@"photo"]];
@try{
//add to mutable array
[photoSmallImageData addObject:[NSData dataWithContentsOfURL:[NSURL URLWithString:photourl]]];
}
@catch (id Exception) {
[photoSmallImageData addObject:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_image]]];
}
//part of table view code
NSData *imageData = [photoSmallImageData objectAtIndex:indexPath.row];
@try {
cell.imageView.image = [UIImage imageWithData:imageData];
}
@catch (NSException *exception) {
cell.imageView.image = [UIImage imageNamed:@"icon72.png"];
}
2.The images are all of diferent sizes and I would like them to have standard look and be centered is there a way to do that and at which point of the code? Thank you very much
EDIT I have found the method: dataWithContentsOfURL:options:error: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html but I don't know how to use it
Upvotes: 0
Views: 282
Reputation: 7344
Why don't you create the images when the image data is downloaded and keep them in the array? Also, you are right to be after the dataWithContentsOfURL:options:error: method. Given that you keep the image names in the dic dictionary, the code would look like this:
NSMutableString *photourl=[[NSMutableString alloc] initWithString:url_image];
[photourl appendString:[dic objectForKey:@"photo"]];
//try to create the image
NSError* err = nil;
UIImage* img = nil;
NSData* tempData = [NSData dataWithContentsOfURL:[NSURL URLWithString:photourl] options:NSDataReadingMappedIfSafe error:&err];
if (!err) {
// image data loaded, create image
img = [UIImage imageWithData:tempData];
} else {
// image data could not be loaded, display error
NSLog(@"%@", err);
// put the default image in the array
img = [UIImage imageNamed:@"icon72.png"];
}
[photoSmallImage addObject:img];
And then in the table view delegate:
cell.imageView.image = [photoSmallImage objectAtIndex:indexPath.row];
As for the second part of your question, you may want to have a look at the contentMode property of UIView class. The default is scale to fill. By manipulating this property on the cell.imageView, you can achieve the effect that you desire.
Upvotes: 2