Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UIImageView Size in UITableViewCell when UIImage loaded from URL?

Loading images from URL into a uiimage and then adding those images to a uitableviewcell uiimageview, like below code. I do not know the image sizes, but need to force them to be 40x40 in the tableviewcell image. The images keep loading with different widths in the uitableview.

Read through other posts related to uiimage sizing/scaling, but those solutions don't work for me. I am thinking it's because I am using the uiimageview included in uitableviewcell vs creating my own uiimageview.

Here's the code>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [[UITableViewCell alloc] init];

ItemForSale *item = [listOfItems objectAtIndex:indexPath.row];
cell.textLabel.text = item.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.font = [UIFont systemFontOfSize:14];

NSURL *url = [NSURL URLWithString: item.imgPath];
UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if (thumbnail == nil) {
    thumbnail = [UIImage imageNamed:@"noimage.png"] ;
}
cell.imageView.image = thumbnail;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
cell.imageView.frame = CGRectMake(0, 0, 40, 40);
cell.imageView.autoresizingMask = UIViewAutoresizingNone;
cell.imageView.clipsToBounds = YES;

return cell;

}

I've tried setting content mode (tried both aspectfill and aspect fit), tried resetting the frame, setting autoresizingmask, clipTobound. none of it changed a thing.

like image 492
Augie Avatar asked Aug 07 '12 13:08

Augie


3 Answers

Found the answer looking at Apples example project "LazyTableImages"

NSURL *url = [NSURL URLWithString: item.imgPath];
UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if (thumbnail == nil) {
    thumbnail = [UIImage imageNamed:@"noimage.png"] ;
}
CGSize itemSize = CGSizeMake(40, 40);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[thumbnail drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return cell;
like image 150
Augie Avatar answered Nov 15 '22 04:11

Augie


I had the same problem and this worked perfectly for me;

select the UIImage and go to attributes inspector and check "Clip Subviews"

make sure you have constraints set for the image's size.

like image 37
NSGodMode Avatar answered Nov 15 '22 05:11

NSGodMode


I had this problem when I was mistakenly using the imageView property of the cell rather than the property for the custom UIImageView I created in the storyboard. When I used the proper reference to the custom view, it all worked as expected. I suspect some of you may have done similar.

like image 1
Litehouse Avatar answered Nov 15 '22 04:11

Litehouse