iosuiimageviewsizetofit

ios - SizeToFit on UIImageView not working


I have a UIImageView which loads in images from the documents directory on the ios file system .

The problem is that when I call

[imageView sizeToFit];

It does not work. I think it is because the image hasn't loaded fully at that point and so the sizeToFit part is called before it has the image width & height.

Could someone point me in the direction of a fix please.

Here is my code:

imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image = [UIImage imageWithContentsOfFile:[FileOperations getLibraryPath:[NSString stringWithFormat:@"%d.png", listData.imageId]]];
[imageView sizeToFit];
[imageScroll setContentOffset:CGPointMake(0, 0)];
imageScroll.contentSize = imageView.frame.size;
imageScroll.decelerationRate = UIScrollViewDecelerationRateFast;
imageScroll.minimumZoomScale = 1;
imageScroll.maximumZoomScale = 2;
[imageScroll setZoomScale:imageScroll.minimumZoomScale];
[imageScroll addSubview:imageView];

Thanks, Ashley


Solution

  • Check the image size:

    NSLog(@"%@", NSStringFromCGSize(imageView.image.size));
    

    You may want to set imageView frame based on the image size manually, for example, if the image is too large to fit the imageView's superview.