如何将数据从嵌套数组推送到tableVIewCell中的collectionVIew

时间:2017-11-01 12:19:19

标签: ios arrays swift

我的布局包含带有海报的集合视图,这些集合视图位于tableviewcells中 我将数据从互联网加载到Array>。第一个数组用于tableviewcell,第二个数组用于collectionview,然后是带有海报URL的结构。我总是从索引中得到错误。

我是iOS开发中的新手,所以任何帮助都会受到赞赏!

这是我的代码:

struct TVShowTitle {
    var id: Int
    var posterPath: String
}

class ForYouViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var tvShowIds: Array<Array<TVShowTitle>> = [[TVShowTitle]]()
var section = 0

var sectionNames = ["Comedy Blockbusters", "Exciting TV", "Horror", "Popular shows", "Sci-fi", "TV Dramas", "Thrillers"]

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return sectionNames.count;
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "SectionCell", for: indexPath) as! SectionTableViewCell

    section = indexPath.row

      cell.sectionNameLabel.text = sectionNames[indexPath.row]
    cell.imageCollectionView.reloadData()
      return cell;
  }


override func viewDidLoad() {
    super.viewDidLoad()

    getTitlesForMostOfTheSections()
}

func getTitlesForMostOfTheSections() {
    // The function loads the URLs for the posters
    self.tableView.reloadData()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

extension ForYouViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell

    if tvShowIds.count <= section && indexPath.row <= tvShowIds[section].count {
             cell.imageView.sd_setImage(with: URL(string: "https://image.tmdb.org/t/p/w300" + tvShowIds[section][indexPath.row].posterPath))
        } else {
             cell.imageView.image = #imageLiteral(resourceName: "placeholder")
        }
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1;
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      // How many shows in a section
    if section > tvShowIds.count || tvShowIds.count == 0 {
        return 0
    } else {
        return tvShowIds[section].count
    }
}
}

0 个答案:

没有答案