首页 > 解决方案 > 在 Swift 中加载图像时应用程序冻结

问题描述

我有这个数组:

media = [  
        [UIImage(named: "1.png")!,UIImage(named: "14.png")!,UIImage(named: "2.png")!],
        [UIImage(named: "3.png")!,UIImage(named: "15.png")!,UIImage(named: "4.png")!],
        [UIImage(named: "5.png")!,UIImage(named: "16.png")!,UIImage(named: "6.png")!],
        [UIImage(named: "7.png")!,UIImage(named: "17.png")!,UIImage(named: "8.png")!],
        [UIImage(named: "9.png")!,UIImage(named: "18.png")!,UIImage(named: "10.png")!],
        [UIImage(named: "11.png")!,UIImage(named: "19.png")!,UIImage(named: "12.png")!],
        [UIImage(named: "13.png")!,UIImage(named: "21.png")!,UIImage(named: "47.png")!]
    ]

我还有一个collectionView

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return media.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return media[section].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MasterViewCell

        cell.thisImage.image = media[indexPath.section][indexPath.row]

        return cell
    }

但我有一个问题。当我滚动我collectionView的应用程序时冻结。但是当我滚动所有部分并继续滚动下一步时。我的应用程序没有冻结。

如何解决?

标签: iosswift

解决方案


为了更好地在 TableView/CollectionView 单元格上加载图像, SDWebImage是完美的图像加载库。将此添加到您的项目中并用于在 collectionView 上加载图像。它将消除图像加载期间的 UI 冻结问题。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MasterViewCell

        cell.thisImage.sd_setImage(with:Bundle.main.url(forResource: "\(indexPath.row + 1)", withExtension:"png"), placeholderImage: UIImage(named: "placeholder.png"))

        return cell
}

希望这会有所帮助。


推荐阅读