如果我想通过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!)
}
我的代码有什么问题吗?
cellForItem(at :)相应索引路径中的单元格对象,如果单元格不可见或indexPath超出范围,则为nil。
您应该使用数据模型titlesArr
来访问数据。