Armand Grillet
Armand Grillet

Reputation: 3399

Manage 800 images using asset catalogs with Xcode and in an UICollectionView

I'm creating an emoji Keyboard with custom images, it has 845 different images (2535 if you're including @1x, @2x and @3x). After importing them to Xcode as assets it is now incredibly slow to compile my program and it takes 3 seconds to display the keyboard in the iOS Simulator.

I also have problem with the UICollectionView I'm using to display the emojis: when I'm scrolling it's crashing. I tried to constrain my UICollectionViewCell as an UIView where its background is the emoji so that I'm not creating a UIImageView but the performances are still poor.

Here is my cellForItemAtIndexPath() function:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
    let emoji = UIImage(named: emojiCollections[collectionUsed][positionInCollection]) // Creating the UIImage with the asset
    let emojiBackgroundColor = UIColor(patternImage: emoji!) // Set the background of the cell.
    positionInCollection++
    return cell
}

With these issues, I would like to know what is the best way to manage this quantity of images and how to display them correctly in a UICollectionView (i.e. with good scrolling performances).

Thank you!

Upvotes: 0

Views: 517

Answers (1)

Kaan Dedeoglu
Kaan Dedeoglu

Reputation: 14841

I assume you're loading all the images and storing them in memory, that is the root of your problems. You should load the emoji images dynamically, only when you need it. UIKit does the caching for you when you load images using UIImage(named:...) method.

As for UICollectionView, using the backgroundColor property for setting the image is not good practice. Make a UICollectionViewCell subclass, with a setBackgroundImage(image: UIImage) method, which sets the image on a UIImageView. In your subclass, you can also do the following to ensure that the old images are unloaded before a cell is reused.

override func prepareForReuse() {
    super.prepareForReuse()
    imageView.image = nil
}

Upvotes: 1

Related Questions