如何用Async图像实现UICollectionViewDelegateFlowlayout的sizeForItemAtIndexPath?

时间:2016-02-19 13:48:41

标签: ios swift uicollectionview

我正在尝试实施类似于本教程的UICollectionViewDelegateFlowlayout sizeForItemAtIndexPathhttp://www.raywenderlich.com/78550/beginning-ios-collection-views-swift-part-1

我遇到的问题是我的照片是通过网络上的异步调用下载的,所以当调用sizeForItemAtItemPath时,我的图片还没有加载。换句话说,下面的代码在imageArray上崩溃了。在加载图像之前,如何延迟方法?如果没有可用的图像,我也尝试使用硬编码和高度值,但是我只返回那些硬编码的值,即加载图像后似乎没有再次调用sizeForItemAtIdexPath

func pinImageForIndexPath(indexPath: NSIndexPath) -> UIImage {
        return imageArray[indexPath.row]
    }



}

extension PinCollectionViewController : UICollectionViewDelegateFlowLayout {
    //1
    func collectionView(collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

            let pinImage =  pinImageForIndexPath(indexPath)
            //2
            if var size = pinImage.size as? CGSize {
                size.width += 10
                size.height += 10
                return size
            }
            return CGSize(width: 100, height: 100)
    }

    //3
    func collectionView(collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        insetForSectionAtIndex section: Int) -> UIEdgeInsets {
            return sectionInsets
    }
}



override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

  let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PinCollectionViewCell

   cell.pinImage?.pin_updateWithProgress = true
   cell.pinImage?.image = nil

    var actInd: UIActivityIndicatorView = UIActivityIndicatorView()
    actInd.frame = cell.pinImage.bounds
    actInd.hidesWhenStopped = true
    actInd.activityIndicatorViewStyle =
        UIActivityIndicatorViewStyle.Gray
    cell.addSubview(actInd)
    actInd.startAnimating()


    if let pinImageURL = self.pins[indexPath.row].largestImage().url {


        cell.pinImage?.pin_setImageFromURL(pinImageURL, completion: ({ (result : PINRemoteImageManagerResult) -> Void in


            actInd.stopAnimating()
            if let image = result.image {
                self.imageArray.append(image)
            }

            self.collectionView?.reloadItemsAtIndexPaths([indexPath])

        }))


    }

    return cell
}

1 个答案:

答案 0 :(得分:1)

实际上,您应该返回一些硬编码值,直到您还没有加载图像。严格来说,你应该为尚未加载的图像显示一些预定义的占位符。

当您的图像被加载时(异步下载操作成功完成),您应该在集合视图上调用-reloadItemsAtIndexPaths:,其中包含这些单元格的索引路径,图像可用。