【发布时间】:2020-02-04 12:36:54
【问题描述】:
我正在使用带有 alamofire 的 youtube api 来获取视频数据(图片 url、标题、描述等)。每当我获取数据并将其附加到我的数组时,单元格都会显示相同的图像。但是当我在“getfeed”方法中打印标题和网址时,显示正确。
查看 cellForItemAtIndexPath。 我认为问题就在这里。 每当我在 cellForItemAt 函数数据重复
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! PhotoCell
//image
let thumbnailUrl = URL(string: videos[indexPath.item].videoThumnailUrl)
cell.imageView.kf.setImage(with: thumbnailUrl)
//prints same title & img url
print("title cell ",videos[indexPath.item].videoTitle)
print("thmbUrl cell",videos[indexPath.item].videoThumnailUrl)
return cell
}
getfeedVideos 函数 但是当我在获取提要功能中打印标题和网址时,它会正确打印。 数据附加在 tempVideos 数组中
func getFeedVideos() {
Alamofire.request(videoURL,
method: .get,
parameters:["part":"snippet",
"regionCode":"US",
"chart":"mostPopular",
"maxResults":3,
"key":API_KEY]).responseJSON {
response in
if response.result.isSuccess {
print("Success! Got the video data")
let videoJSON : JSON = JSON(response.result.value!)
//print(videoJSON)
//creating video object off of JSON response
let videoObj = Video()
var tempVideos = [Video] ()
//loops through all items in videoJson and assigns each value
for (_, value):(String, JSON) in videoJSON["items"] {
videoObj.videoId = value["id"].stringValue
videoObj.videoTitle = value["snippet"]["title"].stringValue
videoObj.videoDescription = value["snippet"]["description"].stringValue
videoObj.videoThumnailUrl = value["snippet"]["thumbnails"]["standard"]["url"].stringValue
//prints different title & img url
print("title ",videoObj.videoTitle)
print("thmbUrl" ,videoObj.videoThumnailUrl)
tempVideos.append(videoObj)
}
self.videos = tempVideos
self.collectionView.reloadData()
} else {
print("Error \(String(describing: response.result.error))")
}
}
}
视频类对象
import UIKit
class Video: NSObject {
var videoId: String = ""
var videoTitle: String = ""
var videoDescription: String = ""
var videoThumnailUrl: String = ""
}
当我运行最终代码时,所有单元格都显示相同的图像。
【问题讨论】:
标签: arrays swift uicollectionview youtube-api