我正在尝试找到一种在UICollectionView上添加youtube视频缩略图集合的方法。但是在我未尝试显示缩略图(图像)的方式上,也没有找到在NSData上添加URL集合(数组)的方法。

或者,如果还有其他方法(例如,使用Youtube API)。

而且,我不了解Obj-C,所以Obj-C中的任何代码都不会很有帮助。

这是我的代码

var videoName:[String] = ["First Video", "Second Video", "Third Video"]
var videoImage:[String] = ["thumbnail1","thumbnail2","thumbnail3"]

let thumbnail1 = NSURL(string: "https://www.youtube.com/watch?v=sGF6bOi1NfA/0.jpg")
let thumbnail2 = NSURL(string: "https://www.youtube.com/watch?v=y71r1jhMdRk/0.jpg")
let thumbnail3 = NSURL(string: "https://www.youtube.com/watch?v=qfsRZsvraD8/0.jpg")

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: SongCollectionView = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! SongCollectionView

    cell.labelCell.text = videoName[indexPath.row]
    let imageData = NSData(contentsOfURL: /*videoImage[indexPath.row]*/ thumbnail1!) // in the commented section I am trying to add an array of strings which contains thumbnail URL's
    cell.imageCell.image = UIImage(data: imageData!)
    return cell
}

最佳答案

使用连音符而不是两个单独的数组的解决方案

let videoData = [("First Video", "sGF6bOi1NfA/0"), ("Second Video","y71r1jhMdRk/0"), ("Third Video", "qfsRZsvraD8/0")]

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  let cell: SongCollectionView = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! SongCollectionView
  let (name, token) = videoData[indexPath.row]

  cell.labelCell.text = name
  let imageData = NSData(contentsOfURL: NSURL(string: "https://www.youtube.com/watch?v=\(token).jpg")!)
  cell.imageCell.image = UIImage(data: imageData)
  return cell
}

10-07 12:23