将TableView中的CollectionView数据传输到新的ViewController

时间:2018-01-02 15:41:33

标签: uitableview swift3 uiviewcontroller uicollectionview delegates

所以我有一个主ViewController,它在TableView中有Horizo​​ntal Scrolling CollectionViews。当您单击CollectionView中的Item时,它会将Item中的所有数据传输到新的ViewController以正确显示它。

我面临的问题是,当您单击CollectionView中的项目时,会执行segue,将数据传输到新ViewController中的数组,但不是仅传输来自特定项目的数据,而是从多个项目发送数据。在一些调试中,我还发现Custom类是加载数组中多个元素而不是segue的东西。这是一些代码。

主VC中的cellForRowAt

if let cell = tableView.dequeueReusableCell(withIdentifier: "HeadlineRow", for: indexPath) as? HeadlineRow {

    cell.latest = self.latest
    cell.collectionView.reloadData()
    cell.delegate = self
    return cell
}

主要VC中的Segue Code

func pushToNewsVC(latestNews: [LatestNews]) {
    self.transferToNewsVC = latestNews
    performSegue(withIdentifier: "NewsVC", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "NewsVC" {
        if let destination = segue.destination as? NewsVC  {
            destination.latestNews.append(contentsOf: self.transferToNewsVC)
            destination.SuggestedLatestNews.append(contentsOf: self.latest)
        }
    }
}

Headlinerow是TableViewCell类

var latest = [LatestNews]()
var transferData = [LatestNews]()

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return latest.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeadlineCell", for: indexPath) as? HeadlineCell {

        let latest = self.latest[indexPath.row]
        cell.updateUI(latest: latest)
        return cell
    }
    return UICollectionViewCell()
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let cell = collectionView.cellForItem(at: indexPath) as? HeadlineCell {
        self.transferData.removeAll()
        self.transferData = cell.transferData
        delegate?.pushToNewsVC(latestNews: self.transferData)
    }
}

HeadlineCell是CollectioViewCell类

var transferData = [LatestNews]()

func updateUI(latest: LatestNews) {
    storyTextView.text = latest.headline
    self.thumbnail.sd_setImage(with: URL(string: "\(latest.app_img)"))
    self.transferData.append(latest)
}

0 个答案:

没有答案