问题
I implemented a CollectionView in a TableViewCell but I need read dynamic data for set cells on CollectionView.
I can read data on extension from class TableViewCell, maybe can help me pass data from ViewController to the class 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)
}
}
回答1:
The simplest way is create one method inside your MultipleTableViewCell
with datasource array that you want to fill with CollectionView
. Now call this method in cellForRowAt
method of 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()
}
}
Now call this method in cellForRowAt
and pass the datasource array for 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
}
来源:https://stackoverflow.com/questions/42651196/how-pass-data-to-an-uicollectionview-embedded-in-a-tableviewcell-xcode-ios