如何将数据传递给嵌入在TableViewCell中的UICollectionView(xCode - iOS - Swift 3)

jar*_*rns 1 xcode uitableview ios uicollectionview swift3

我在TableViewCell中实现了CollectionView,但我需要在CollectionView上读取set单元格的动态数据.

我可以从类TableViewCell读取有关扩展的数据,也许可以帮助我将数据从ViewController传递到类TableViewCell.

 class MultipleTableViewCell: UITableViewCell {

        @IBOutlet fileprivate weak var collectionView: UICollectionView!

    }

    extension MultipleTableViewCell : UICollectionViewDataSource {

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

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

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

     let dict = array.object(at: indexPath.row) as! NSDictionary //Like this

            cell.name.text = "How do you read data from ViewController"
            cell.email.text = "How do you read data from ViewController"
            cell.phone.text =  dict["phone"] as? String //Like this
            cell.image.image = "How do you read data from ViewController"

            return cell
        }

    }

    extension MultipleFoodTableViewCell : UICollectionViewDelegateFlowLayout {

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

            let itemsPerRow:CGFloat = 1
            let hardCodedPadding:CGFloat = 20
            let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
            let itemHeight = collectionView.bounds.height - (2 * hardCodedPadding)
            return CGSize(width: itemWidth, height: itemHeight)
        }

    }
Run Code Online (Sandbox Code Playgroud)

Nir*_*v D 9

最简单的方法是在您MultipleTableViewCell要填充的数据源数组中创建一个方法CollectionView.现在在cellForRowAt方法中调用此方法TableView.

class MultipleTableViewCell: UITableViewCell {

     @IBOutlet fileprivate weak var collectionView: UICollectionView!

     var array = [String]() //Change with Your array type

     func fillCollectionView(with array: [String]) {
          self.array = array
          self.collectionView.reloadData()
     }
}
Run Code Online (Sandbox Code Playgroud)

现在调用此方法cellForRowAt并传递数据源数组collectionView.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier") as! MultipleTableViewCell
    cell.fillCollectionView(with: ["A","B","C"]) //Pass your array
    return cell
}
Run Code Online (Sandbox Code Playgroud)