UICollectionView第二次没有加载单元格

时间:2017-11-30 09:55:24

标签: ios swift uicollectionview

我正在使用UICollectionview照常列出一些图片。

代码只是从api获取数据并异步更新UICollectionView。 API调用代码的结尾是使用self.collectionView?.reloadData()更新数据。

当用户滚动到UICollectionView api的底部时,再次触发呼叫并更新photos数组和集合视图数据。但是在第二个动作中没有向UICollectionView

添加新单元格

这是代码:

class PhotoStreamViewController: UICollectionViewController {
    var photos = [Photo]()
    var pageIndex = 1
    ...


    override func viewDidLoad() {
        super.viewDidLoad()
        allPhotos()
        ...

    }
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        pageIndex+=1
        allPhotos()
    }


    func allPhotos() {

        let headers: HTTPHeaders = [
            "Authorization": "Client-ID APIKEY"
        ]

        var json:JSON = JSON()

        Alamofire.request("https://www.apiurl.com/photos?page=\(pageIndex)&per_page=15&order_by=latest",method: .get, parameters: nil , encoding: URLEncoding.default, headers: headers)
            .responseJSON() { (response:DataResponse<Any>) in
                //            debugPrint(response)
                switch response.result {
                case .success(let value):
                    json = JSON(value)

                    for (_,subJson):(String, JSON) in json {
                        let image = UIImage(data: try! Data(contentsOf: URL(string: subJson["urls"]["small"].stringValue)!))

                        if let photo = Photo(userName: subJson["user"]["name"].stringValue,comment: "dummy",image: image!,location: "Location",thumb: "thumb") {
                            self.photos.append(photo)
                        }
                    }

                    self.collectionView?.reloadData()


                case .failure(let error):
                    print(error)
                }
        }
    }

}

extension PhotoStreamViewController : UICollectionViewDelegateFlowLayout{

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.photos.count
    }


    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AnnotatedPhotoCell", for: indexPath as IndexPath) as! AnnotatedPhotoCell
        cell.photo = photos[indexPath.item]
        return cell
    }

}

4 个答案:

答案 0 :(得分:0)

你需要在主队列中重新加载你的集合视图。请试试这个。我认为它可以解决你的问题

enumerate

答案 1 :(得分:0)

self.photos.append(photo)

下添加此代码后问题已解决
  if(self.pageIndex > 1){
     let indexPath = IndexPath(item:self.photos.count-1, section: 0)
     self.collectionView?.insertItems(at: [indexPath])

  }

我也有扩展名:

extension PhotoStreamViewController : PinterestLayoutDelegate

PinterestLayout内自定义layoutattributes后,它运行良好

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

答案 2 :(得分:0)

尝试

if let layout = self.IBcollection?.collectionViewLayout as? PInterestLayout 
{
      layout.cache = []
      layout.columnsYoffset = []
      layout.contentSize = CGSize.zero
}
self.IBcollection.reloadData()

答案 3 :(得分:0)

打开PinterestLayout

检查 prepare 函数。它包含以下行。其中 cache 为空。每当它重新加载时,它就会变成 cache 空。

guard cache.isEmpty == true,let collectionView = collectionView else {return}

用这个替换上面的代码:

guard let collectionView = collectionView else {return}
cache.removeAll() // Add this line while changing in array elements.