ios - UICollectionView 加载较晚并且滚动非常颠簸

标签 ios swift scroll uicollectionview

我正在设计一个 Collection View ,在其中尝试加载存储在数组中的字典中的图像和文本。我的主数组在这里,即 bannerarray 正在其他函数中进行解析。但我遇到的问题是,当我滚动它来加载图像时,我的 Collection View 变得不稳定,就好像滚动道路上有颠簸一样。我寻找了各种答案和代码,但没有一个能解决我的问题。

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell = myCollectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! LandingPageCVC


        dispatch_async(dispatch_get_main_queue(),
            {
                let categoryname = self.categoriesarray.objectAtIndex(indexPath.row).valueForKey("name")

                cell.layer.shouldRasterize = true;
                cell.layer.rasterizationScale = UIScreen.mainScreen().scale



                let imageurl = self.categoriesarray.objectAtIndex(indexPath.row).valueForKey("image") as! String

                if let url  = NSURL(string: imageurl),
                    data = NSData(contentsOfURL: url)
                {

                    cell.lndngimage.image = UIImage(data: data)
                }
                if indexPath.row % 2 == 0
                {
                    cell.backgroundColor = UIColor(red: 67/255.0, green: 179/255.0, blue: 246/255.0, alpha: 1.0)
                }
                else if indexPath.row % 3 == 0 && indexPath.row%2 != 0
                {
                    cell.backgroundColor = UIColor.redColor()
                }
                else
                {
                    cell.backgroundColor = UIColor.greenColor()
                }
                cell.lndngimg.text = categoryname as? String

        })



        return cell
    }

请帮忙!提前致谢。

最佳答案

let queue = dispatch_queue_create("loader", nil)
dispatch_async(queue) { () -> Void in
//download the image do stuff
//like data = NSData(contentsOfURL: url)

//move back in main thread
dispatch_async(dispatch_get_main_queue(),{
    //set the image.
    //cell.lndngimage.image = UIImage(data: data)
     })
 }

因此 data = NSData(contentsOfURL: url) 在主线程中下载图像,这就是为什么 UICollectionView 加载较晚或可能会阻塞,只需做一件事创建下载图像的队列并将其设置在主线程中。

关于ios - UICollectionView 加载较晚并且滚动非常颠簸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677709/

相关文章:

ios - 如何在 iOS 中创建非圆角 UIProgressView

ios - 删除行时TableView "unrecognized selector sent to instance"错误

jQuery:根据窗口滚动位置固定到页面顶部后动画容器宽度

ios - 这些不同的 dealloc 策略的优缺点是什么?

ios - 识别哪个View调用Tap函数

ios - 使用 selenium-objective-c 框架

ios - UIImagePickerController 不请求许可

javascript - 我希望我的登录弹出窗口不显示底部的滚动条

javascript - 同时向下滚动一个 div 和向上滚动一个?

ios - Xcode 中的内存管理