Skip to content

UIKit extensions and autolayout

hpique edited this page Oct 13, 2014 · 4 revisions
imageView.setImageFromURL(URL) 

When using Haneke from the UIKit extensions, Haneke will attempt to show the image at the smallest size needed. This reduces memory consumption and might be the most important reason why Haneke performs better than other image caches.

In order to calculate the size in which the image will be displayed, Haneke needs to know the view bounds, or rely on you providing this information via a custom format. We'll get to that in a minute.

There are some cases in which the view bounds might not be known at the time of calling the extension functions (e.g, UIImageView.hnk_setImageFromURL). Some of them involve autolayout, and the simplest solution is to make sure layoutIfNeeded is called before Haneke.

layoutIfNeeded is a potentially expensive call, and perhaps you would like Haneke to start working before layout. This can be achieved by using formats. If the final size of the view is known (e.g., 100x100), then you can simply do:

imageView.setImageFromURL(URL, format: Format<UIImage>("100x100") {
    let resizer = ImageResizer(size: CGSizeMake(100,100),
        scaleMode: self.hnk_scaleMode,
    )
    return resizer.resizeImage($0)
}) 

Note that we're using the ImageResizer convenience class, but we could have used any other transformation. Also note that we're using a convenience function (UIImageView.hnk_scaleMode) to pick the best scaling mode based on the content mode of the view. There are other options that can be configured, such as compression quality and cache disk size.

What if you don't know the final size of the view? Maybe you're dealing with a dynamic view size, or maybe you don't want to resize images at all. Then you're better off working with the original image, like this:

imageView.setImageFromURL(URL, format: Format<UIImage>("original")) 

This works because formats don't perform any transformation by default. It's worth mentioning that the format name doesn't have any effect on how the format behaves. The only important thing is to use the same format name in every other place in which you want to reuse the same images.

Clone this wiki locally