Swift-在我尝试通过cellForItem访问项目时,我的项目中为零

时间:2019-03-05 05:19:34

标签: ios swift uicollectionview uicollectionviewcell

如果我想通过UICollectionViewItem来获取商品,我的cellForItem中将得到零。但是数据显示在我的UICollectionView中。 我正在通过遥控器在UICollectionView中显示数据。当我尝试通过项目访问数据时,在reloadData之后。它返回nil。

这里是用于从远程获取数据并重新加载Collection View的代码。

    URLSession.shared.dataTask(with: url!) { (data, response, err) in
        guard let data = data else { return }

        do {

            let songs = try JSONDecoder().decode(yt.self, from: data)
            for sng in songs.items {
                if(sng.id.videoId==nil){
                    self.video_arr.append("xVrNFaeMvP8")

                    self.images.append("https://i.ytimg.com/vi/sGIm0-dQd8M/default.jpg")
                }else{
                    self.video_arr.append(sng.id.videoId)
                    self.images.append(sng.snippet.thumbnails.medium.url)
                }
                self.channelTitle.append(sng.snippet.channelTitle)
                self.titlesArr.append(sng.snippet.title!)

            }
            DispatchQueue.main.async() {
                self.collectionView.reloadData()
                self.isAddedToFavourites()
            }

            SVProgressHUD.dismiss()

        } catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }

        }.resume()

这是我要获取商品的代码。

func isAddedToFavourites(){
    for i in 0..<collectionView.numberOfItems(inSection: 0) - 1{
        let indexPath = IndexPath(row: i, section: 0)
        let item = collectionView.cellForItem(at: indexPath) as! PlayerCollectionViewCell
        //This is returning nil
       print(item.musicTitle.text!)
    }

我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

  

cellForItem(at:):位于相应索引路径的单元格对象;如果该单元格不可见或indexPath超出范围,则为nil。

您应该使用数据模型titlesArr来访问数据。

引用UICollectionview cellForItem return nil

相关问题