Swift - 在我的项目中获取nil,而我试图通过cellForItem访问项目

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

如果我想通过UICollectionViewItem获取我的物品,我的cellForItem正在变零。但数据显示在我的UICollectionView中。我通过遥控器在我的UICollectionView中显示数据。在reloadData之后我尝试通过item访问数据。它返回零。

这是从远程获取数据并重新加载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!)
    }

我的代码有什么问题吗?

ios swift uicollectionview uicollectionviewcell
1个回答
0
投票

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

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

请参阅UICollectionview cellForItem return nil

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