Jim McDermott
Jim McDermott

Reputation: 255

Swift slow collectionView

I have a collection view that takes images I have stored and displays them. However, when I run it, I get a memory error and a really slow/laggy display. Here is my code:

var players = ["1", "2", "3", "4", "5", "10", "11", "12", "13", "15", "20", "22", "24", "25", "31", "31", "33", "34"]


@IBOutlet weak var collectionView: UICollectionView!
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return 17


}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as HomeCollectionViewCell
    cell.imageViewTwo.image = UIImage(named: "\(players[indexPath.row])")
    return cell
}

Is there an easier way to do this that I'm missing?

Upvotes: 0

Views: 1687

Answers (1)

matt
matt

Reputation: 534950

You should use Instruments to figure out what it is that is slow. That's what it's for!

However, I'm going to guess that this line is the problem:

cell.imageViewTwo.image = UIImage(named: "\(players[indexPath.row])")

If those images are big, two bad things will happen: it takes time to open each one, and you are wasting memory because the displayed image is much smaller than the loaded image. And this is happening while you scroll. Everything you do in cellForItemAtIndexPath: needs to be very, very fast for exactly this reason. Well, your implementation is clearly not fast.

You have two choices - actually you could use both:

  • Prepare better images. Use png and use them at the actual size needed for display.

  • Use lazy image loading so that you load the images in a background thread and don't slow down the scrolling.

Upvotes: 3

Related Questions