7
votes

I have a tableView with rows that need to be horizontally flowing collectionViews.

My tableView cells have a single collectionView within them, and then I instantiate them like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell", forIndexPath: indexPath) as! MyTableViewCell
    let nibName = UINib(nibName: "CollectionCell", bundle: nil)
    cell.collectionView.registerNib(nibName, forCellWithReuseIdentifier: "CollectionCell")
    cell.collectionView.dataSource = self
    cell.collectionView.delegate = self

    return cell
}

I'm trying to use an auto-height table view row, and I think this is what could be causing issues. How do I use UITableViewAutomaticDimension with internal collection views?

2
You may probably need to call reloadData after you have set the delegate and datasource - Qazi
@Qazi did that in cellForRowAtIndexPath, no effect. - Stefan Kendall
sorry I was not clear, so you are calling the reloadData on collection view right and not on the TableView? - Qazi
@Qazi Yup. On the collection view. - Stefan Kendall

2 Answers

7
votes

This is in objective-c, but works for me:

i. In your custom cell's .m file register the UICollectionViewCell nib, and specify you layout details (size, spacing etc.).

ii. in the VC that holds the tableView its .m do the following in cellForRowAtIndexPath

 MyTableViewCell *cell = (MyTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"MyTableViewCellId" forIndexPath:indexPath];

    cell.collectionView.delegate = self;
    cell.collectionView.dataSource = self;
    cell.collectionView.tag = indexPath.row;

    [cell.collectionView reloadData];

iii. You can use the tag of the UICollectionView in the delegate methods to populate the right information

Hop this helps.

0
votes

Try adding - cell.setTranslatesAutoresizingMaskIntoConstraints(false) - see below

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell", forIndexPath: indexPath) as! MyTableViewCell
    let nibName = UINib(nibName: "CollectionCell", bundle: nil)
    cell.collectionView.registerNib(nibName, forCellWithReuseIdentifier: "CollectionCell")
    cell.collectionView.dataSource = self
    cell.collectionView.delegate = self
    cell.setTranslatesAutoresizingMaskIntoConstraints(false)

    return cell
}

See https://www.captechconsulting.com/blogs/ios-8-tutorial-series-auto-sizing-table-cells for some more information.