I am getting nil in my UICollectionViewItem
if I am trying to get my item via cellForItem
. But data is showing in my UICollectionView
. I am displaying data in my UICollectionView
via remote. after reloadData
when I try to access data via item. it returning nil.
Here's code for fetching data from remote and reload 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()
and Here's my code where I am getting my item.
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!)
}
is there anything wrong with my code?
cellForItem(at:) The cell object at the corresponding index path or nil if the cell is not visible or indexPath is out of range.
You should use the data model titlesArr
to access the data instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.