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.
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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With