当reloadData时,UICollectionView滚动性能会降低

问题描述 投票:0回答:2

我有一个UICollectionView,当我向其添加固定数据时,它应该运行,但如果我再次重新加载它(从服务获取数据)滚动变慢或者它可能停止滚动。

这是代码:

@IBOutlet var myCollectionView: UICollectionView!

func getAllCategories() {
        API.categories { (error: Error?, success: Bool,  categories: [Category]) in
            if success {
                self.categories = categories
                print("success")
                self.myCollectionView.reloadData()
            } else {
                print("failed")
            }
        }
    }

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if(self.categories.count > 0) {
            return (self.categories.count - 1)
        } else {
            return 0
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as! HomeCollectionViewCell

        cell.containerCollectionView.layer.cornerRadius = 20
        cell.containerCollectionView.layer.borderWidth = 2
        cell.containerCollectionView.layer.borderColor = UIColor(red:219/255.0, green:219/255.0, blue:219/255.0, alpha: 0.5).cgColor;
        cell.containerCollectionView.layer.masksToBounds = true
        if(self.categories.count > 0) {
            cell.category_name.text = self.categories[indexPath.row + 1].name
            cell.adds_number.text = String(self.categories[indexPath.row + 1].ads_count) + " إعلان"
            cell.fav_number.text = String(self.categories[indexPath.row + 1].fav_count) + " مفضلة"
            ////// to load URLs images //////
                let imageUrl = "http://xxxxxxxx.com/images/categories/" + self.categories[indexPath.row + 1].image
                let url = URL(string: imageUrl)
                let image = NSData(contentsOf: url!)
                if(image != nil){
                    cell.categoryImageView.image = UIImage(data: image! as Data)
                }
        }
        return cell
    }

我案的任何解决方案?

ios swift swift4
2个回答
1
投票

以下代码的问题:

////// to load URLs images //////
            let imageUrl = "http://souqsahm.com/images/categories/" + self.categories[indexPath.row + 1].image
            let url = URL(string: imageUrl)
            let image = NSData(contentsOf: url!)
            if(image != nil){
                cell.categoryImageView.image = UIImage(data: image! as Data)
            }

尝试在后台线程中下载图像,或者您可以使用此api qazxsw poi


1
投票

问题出在这里

https://github.com/rs/SDWebImage

这应该是在 let image = NSData(contentsOf: url!) 不是主要的,因为这行阻止mainQueue直到从url获取的图像的数据,这导致加载DispatchQueue.global.async的延迟

© www.soinside.com 2019 - 2024. All rights reserved.