UICollectionView inside a UITableViewCell -- dynamic height?
Asked Answered
I

16

145

One of our application screens requires us to place a UICollectionView inside of a UITableViewCell. This UICollectionView will have a dynamic number of items, resulting in a height which must be calculated dynamically as well. However, I am running into problems trying to calculate the height of the embedded UICollectionView.

Our overarching UIViewController was created in Storyboards and does make use of auto layout. But, I don't know how to dynamically increase the height of the UITableViewCell based on the height of the UICollectionView.

Can anyone give some tips or advice on how to accomplish this?

Iny answered 9/6, 2014 at 18:39 Comment(4)
can you tell a bit more about the layout you're trying to accomplish ? Is the height of the UITableViewCell different from its acutal tableview ? Do you need vertical scrolling on both the UICollectionView and the UITableViewTobar
The height of the UITableViewCell is supposed to be dynamic, based on the height of the UICollectionView that is part of the table view cell. The layout of my UICollectionView is 4 columns and a dynamic number of rows. So, with 100 items, I would have 4 columns and 25 rows in my UICollectionView. The height of the particular cell -- as indicated by UITableView's heightForRowAtIndexPath -- needs to be able to adjust based on the size of that UICollectionView. Is that a bit more clear?Iny
@Iny , please suggest me a solution for this situationDecosta
I combined a few concepts that I've read about to achieve something similar. See my answer in https://mcmap.net/q/161038/-how-to-resize-a-horizontal-uicollectionview-height-based-on-its-content-in-a-uitableviewcellNonfiction
Z
141

The right answer is YES, you CAN do this.

I came across this problem some weeks ago. It is actually easier than you may think. Put your cells into NIBs (or storyboards) and pin them to let auto layout do all the work

Given the following structure:

TableView

TableViewCell

CollectionView

CollectionViewCell

CollectionViewCell

CollectionViewCell

[...variable number of cells or different cell sizes]

The solution is to tell auto layout to compute first the collectionViewCell sizes, then the collection view contentSize, and use it as the size of your cell. This is the UIView method that "does the magic":

-(void)systemLayoutSizeFittingSize:(CGSize)targetSize 
     withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority 
           verticalFittingPriority:(UILayoutPriority)verticalFittingPriority

You have to set here the size of the TableViewCell, which in your case is the CollectionView's contentSize.

CollectionViewCell

At the CollectionViewCell you have to tell the cell to layout each time you change the model (e.g.: you set a UILabel with a text, then the cell has to be layout again).

- (void)bindWithModel:(id)model {
    // Do whatever you may need to bind with your data and 
    // tell the collection view cell's contentView to resize
    [self.contentView setNeedsLayout];
}
// Other stuff here...

TableViewCell

The TableViewCell does the magic. It has an outlet to your collectionView, enables the auto layout for collectionView cells using estimatedItemSize of the UICollectionViewFlowLayout.

Then, the trick is to set your tableView cell's size at the systemLayoutSizeFittingSize... method. (NOTE: iOS8 or later)

NOTE: I tried to use the delegate cell's height method of the tableView -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath.but it's too late for the auto layout system to compute the CollectionView contentSize and sometimes you may find wrong resized cells.

@implementation TableCell

- (void)awakeFromNib {
    [super awakeFromNib];
    UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;

    // Configure the collectionView
    flow.minimumInteritemSpacing = ...;

    // This enables the magic of auto layout. 
    // Setting estimatedItemSize different to CGSizeZero 
    // on flow Layout enables auto layout for collectionView cells.
    // https://developer.apple.com/videos/play/wwdc2014-226/
    flow.estimatedItemSize = CGSizeMake(1, 1);

    // Disable the scroll on your collection view
    // to avoid running into multiple scroll issues.
    [self.collectionView setScrollEnabled:NO];
}

- (void)bindWithModel:(id)model {
    // Do your stuff here to configure the tableViewCell
    // Tell the cell to redraw its contentView        
    [self.contentView layoutIfNeeded];
}

// THIS IS THE MOST IMPORTANT METHOD
//
// This method tells the auto layout
// You cannot calculate the collectionView content size in any other place, 
// because you run into race condition issues.
// NOTE: Works for iOS 8 or later
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority verticalFittingPriority:(UILayoutPriority)verticalFittingPriority {

    // With autolayout enabled on collection view's cells we need to force a collection view relayout with the shown size (width)
    self.collectionView.frame = CGRectMake(0, 0, targetSize.width, MAXFLOAT);
    [self.collectionView layoutIfNeeded];

    // If the cell's size has to be exactly the content 
    // Size of the collection View, just return the
    // collectionViewLayout's collectionViewContentSize.

    return [self.collectionView.collectionViewLayout collectionViewContentSize];
}

// Other stuff here...

@end

TableViewController

Remember to enable the auto layout system for the tableView cells at your TableViewController:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Enable automatic row auto layout calculations        
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // Set the estimatedRowHeight to a non-0 value to enable auto layout.
    self.tableView.estimatedRowHeight = 10;

}

CREDIT: @rbarbera helped to sort this out

Zoie answered 27/10, 2015 at 9:26 Comment(36)
Question, how do you link the tableview and the collectionview in the storyboard? I assume you use a segue but i cannot choose which one. Also i'm coding in swift so i'm already struggling with the traduction of the codeLimbate
I create a NIB for the UITableViewCell, and a custom subclass for that cell (E.g. PRTableCell), then I put a UICollectionView -NOT a UICollectionViewController- inside the cell with auto layout constraints. Then I create an outlet for the collectionView into the PRTableCell. If you want to use storyboard, simply do the same with a cell Prototype and using a custom class.Zoie
Yeah. This works. This should be the accepted answer.Kerek
I can't get this to work in Swift. I have exactly the same problem, I used ashfurrow.com/blog/… as a guide. But having a "fixed" dynamic height doesnt seem to work for me.Vastitude
Can any body provide me a sample code for it? i want to show multiple images in vertical collection view , which is inside of tableview cell..Decosta
@PabloRomeu can you please explain it in sample , i am new in iosDecosta
@PabloRomeu Great right up, this really helped me. Thank youMaximin
@PabloRomeu, My long search ends here. ThanksJoplin
Finally this is worked for me, but I had to do an other trick: cell.bounds = CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), 10000); This will "simulate" a long cell with a long collectionView, so the collectionView will compute the size all of its cells. Otherwise the collectionView computed only the visible cell sizes, and set wrongly the talbeViewCell height.Both
If you have a collectionView with elements located outside of the collectionView, it's real size won't be computed, the estimatedSize will be used instead of this. The real size will be computed only if these cell will be visible, bat that's too late, because at this point your tableViewCell has a wrong height setup already. So no, the estimatedSize won't do the trickBoth
Question (before I go and try this solution): In my case, the collection view is PART of the cell. The cell has other components and currently Autolayout is calculating the cell height for me, since the other components are dynamic. So far the collection view has a fixed height, but I want to make it dynamic too. Will this work? How? My idea is to use this method to change a height constraint for the collection view, not for the cell.... is that the right path?Vadose
@Vadose I made it work using a height constraint on the collection view in the systemLayoutSizeFittingSize method. collectionViewHeightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize().height then return self.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)Thrombosis
@ingaham Exactly, the cell.bounds trick is the most important part. I am using a tableView inside a tableView cell (almost the same setup) and without setting the outer table's cell.bounds to some huge height it doesn't compute the contentSize correctly.Fong
I'm trying this way but the only thing I've got is the app to freeze :( @ingaham Where did you place that cells.bouds statement?Opalescent
@WedgeSparda: When I'm configuring the cell in the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath). I'm setting at first the cell.bounds, then the full cell layout will be configuredBoth
@ingaham Tried that, but have the same problem. If I scroll quickly the height of the cell containing the collectionView if not correct. After a reloadData on the tableView the cell gets the correct height. Is really weird.Opalescent
@PabloRomeu, Hello bro, Could you help me to look at my question #44541903 bro?Adamsen
@PabloRomeu by this methos the collection has some extra spaces. how to get rid of it. When we have to bindWithModel mentioned in your codeAdan
bindWithModel means you have to set your model to your cell there. That's important because maybe you have to setup -for example- a UILabel that may change the cell's size.Zoie
when setting the frame height to maximum in systemLayoutSizeFittingSize, i hit a problem in swift when reloading the cell, apps seems to stuck after the self.collectionView.layoutIfNeeded(). I fixed it by setting the frame height with 1 rather than maximum height. Hope its helps if anyone stumble in this problem.Plenum
What if my CollectionView's flow is horizontal? In that case, the collectionViewCell can grow vertically?Carboniferous
@Nil It will. My collection view had no flow and was multiline, I grew up the tableViewCell to the full size of the collection so it can fit fully inside.Zoie
@PabloRomeu I'm having same issue as @WedgeSparda, and I can see why: in systemLayoutSizeFittingSize right before calling layoutIfNeeded on the collectionview, I can see that self.bounds (the bounds of the tableview cell) has a width of 363 pixels. But after calling layoutIfNeeded on the collectionview, the size of the collectionview (contentSize, or frame) has a larger width (606 pixels), even though it is pinned with constraints to the inside of the tableview cell. Thus the first time systemLayoutSizeFittingSize returns a value, the value is wrong.Psychogenesis
@Psychogenesis that's because the table cell is still not still at full size...Zoie
Here's what fixed it for me - in systemLayoutSizeFitting, reverse the order of what's shown in the answer currently, so that first collectionView.layoutIfNeeded() runs, then collectionView.frame = CGRect.init(origin: .zero, size: CGSize.init(width: targetSize.width, height: 1))Psychogenesis
I have a UIView inside the TableViewCell and inside that view, I place the collectionView. I create a subclass of this view. This subclass of UIView is the datasource and delegate for collectionView and am putting in the systemLayoutSizeFitting method inside that view subclass however, it is not working. I have the outlet of UIView subclass inside my TableViewCell and outlet for the collectionView inside the UIView subclass.Lectern
Does anybody know how to make it work in Swift with Autolayout? Are there any examples? Thank you!Rone
@AlexeyChekanov here is my code, I'm setting constraints with AutoLayout on my Storyboard and using their outlets in my code. My cell has a label and under it a collection view with varying number of buttons in different sizes. So I'm letting Autolayout set the position of things and then taking all heights together for the cell height size. Please see: gist.github.com/boazFrenkel/35b875f5d026e96981225dfcc9ad0623Buck
This is a great answer! Also @titan's comment is very importantVelocity
Just noticed. Sometimes it doesn't work. Doesn't size the table view cell to take the whole collection view heightVelocity
Not working for horizontal scroll. TableView Cell is not resizing.Seamark
I have copied this solution exactly except I am using a horizontal scroll on the CollectionView. I cant get it to work. Any ideas?Kairouan
This worked for me. Not sure why. override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { collectionView.layoutIfNeeded() collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width, height: 1) collectionView.layoutIfNeeded() return collectionView.contentSize }Aubade
This Worked for me. Call super.systemLayoutSizeFitting inside tableview systemLayoutSizeFitting method. in addition no need to assign collection view.frameGoatsbeard
I've only overwrite systemLayoutSizeFittingSize to make it work and didn't use estimatedSize only itemSize, thank you. Also, why did you setNeedsLayout in the collection cell ? You already layoutIfNeeded in the tableviewcell systemLayoutSizeFittingSize and the bindWithModel @PabloRomeuLebrun
This did not work for me...Delvalle
B
117

I think my solution is much simpler than the one proposed by @PabloRomeu.

Step 1. Create outlet from UICollectionView to UITableViewCell subclass, where UICollectionView is placed. Let, it's name will be collectionView

Step 2. Add in IB for UICollectionView height constraint and create outlet to UITableViewCell subclass too. Let, it's name will be collectionViewHeight.

Step 3. In tableView:cellForRowAtIndexPath: add code:

// deque a cell
cell.frame = tableView.bounds;
[cell layoutIfNeeded];
[cell.collectionView reloadData];
cell.collectionViewHeight.constant = cell.collectionView.collectionViewLayout.collectionViewContentSize.height;
Bitchy answered 17/7, 2016 at 21:33 Comment(18)
Have you actually tried this? It doesn't seem possible to both set a height constraint on the collection view and pin it to the margins of the table view cell. You either end up with too few constraints (hence a zero size warning), or you end up with conflicting constraints (one of which is ignored). Please explain how to set the constraints for this solution.Lach
I have it worked. I add constraints for collectionView to all sides of UITableViewCell and set tableView.estimatedRowHeight = 44; and tableView.rowHeight = UITableViewAutomaticDimension;Bitchy
This one works like champ...simple and efficient...thank you. If for somebody it is not working then probably the reason might be, we need to bind the bottom of collection view to bottom of table view cell. Then it will start working. Happy coding..:)Inclusive
Would this work when the screen is resized, say by rotating an iPad? That would potentially change the height of the collection view, and therefore the height of the cell, but if on-screen the cell may not necessarily be reloaded by the table view, thus never calling the cellForRowAtIndexPath: method and not giving you a chance to change the constraint constant. It may be possible to force a reloadData though.Criner
I think, yes, it's needed to force reloadData on change Interface orientation.Bitchy
Have you tried different collectionView cell's sizes? That was my problem. If you have different collectionView's cell sizes it did not work... :(Zoie
Does someone have this working in a sample project they could share?Okapi
@PabloRomeu, I am facing same problem. Any solution?Joplin
@Bitchy I'm running into a similar issue..can you assist me with my question? #45177247Clementineclementis
There's a different EASIER approch for this, just implment the last line of your code in the table cell's layoutSubviews() classFullmer
I needed to adapt your solution a bit, but it worked in the end! What I did was reverse the order of these two lines: [cell layoutIfNeeded]; [cell.collectionView reloadData];Rheims
this will work But my problem is that inside the collection view I have another collection view and the main collection view has just two page (paging mode) and each page has collection view how can I handle that ?Impunity
@Igor, Do you have any sample code for this? Because I have tried and it won't work for me... It would be great if you can provide any sample code for it.Careless
The collectionView reload is taking time and if i change my font size of labels inside the collectionview cell and reload, the latest contentsize is not reflected.Petiolate
What I don't understand is what this line cell.frame = tableView.bounds; for. Can anybody explain this please?Velocity
I was using a collectionView inside a collectionViewCell and I couldn't achieve the dynamic height behaviour I wanted. I changed the encapsulating collectionView with a tableView, and now I had a structure like the one described by OP. This method was the only one that worked for me! Thanks @BitchyRheims
This is useful for me like one table view than use CollectionViewCell and tableview inside my tableview. nice work .Gavette
Beast solution. Thank you!Sharyl
M
22

Both table views and collection views are UIScrollView subclasses and thus don't like to be embedded inside another scroll view as they try to calculate content sizes, reuse cells, etc.

I recommend you to use only a collection view for all your purposes.

You can divide it in sections and "treat" some sections' layout as a table view and others as a collection view. After all there's nothing you can't achieve with a collection view that you can with a table view.

If you have a basic grid layout for your collection view "parts" you can also use regular table cells to handle them. Still if you don't need iOS 5 support you should better use collection views.

Mesopotamia answered 16/6, 2014 at 8:30 Comment(5)
You've put "treat" in quotes, because you can NOT define different layouts per CollectionView section, right? I haven't found an option to define different layouts for different collection view sections. Am I overlooking something or are you talking of responding differently to 'layoutAttributesForItemAtIndexPath' for different sections in my own custom subclass of UICollectionViewLayout?Guenzi
Yes -> Are you talking of responding differently to layoutAttributesForItemAtIndexPath for different sections in my own custom subclass of UICollectionViewLayout?Mesopotamia
@Rivera, your answer is most reasonable and sounds just correct. I have read this suggestion on many places. Could you also share some link to sample or tute on how to accomplish that or at least some pointers. TIACranky
Your answer assumes you are starting from scratch, and don't already have a big complex tableview that you need to fit into. The question specifically asked about putting a collectionview in a tableview. IMO your response is not an "answer"Psychogenesis
This is a bad answer. Having collection views inside table views is such a common thing to do, almost every app does it.Kellar
B
14

Pablo Romeu's answer above (https://mcmap.net/q/158507/-uicollectionview-inside-a-uitableviewcell-dynamic-height) helped me immensely with my issue. I had to do a few things differently, however, to get this working for my problem. First off, I didn't have to call layoutIfNeeded() as often. I only had to call it on the collectionView in the systemLayoutSizeFitting function.

Secondly, I had auto layout constraints on my collection view in the table view cell to give it some padding. So I had to subtract the leading and trailing margins from the targetSize.width when setting the collectionView.frame's width. I also had to add the top and bottom margins to the return value CGSize height.

To get these constraint constants, I had the option of either creating outlets to the constraints, hard-coding their constants, or looking them up by an identifier. I decided to go with the third option to make my custom table view cell class easily reusable. In the end, this was everything I needed to get it working:

class CollectionTableViewCell: UITableViewCell {

    // MARK: -
    // MARK: Properties
    @IBOutlet weak var collectionView: UICollectionView! {
        didSet {
            collectionViewLayout?.estimatedItemSize = CGSize(width: 1, height: 1)
            selectionStyle = .none
        }
    }

    var collectionViewLayout: UICollectionViewFlowLayout? {
        return collectionView.collectionViewLayout as? UICollectionViewFlowLayout
    }

    // MARK: -
    // MARK: UIView functions
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        collectionView.layoutIfNeeded()

        let topConstraintConstant = contentView.constraint(byIdentifier: "topAnchor")?.constant ?? 0
        let bottomConstraintConstant = contentView.constraint(byIdentifier: "bottomAnchor")?.constant ?? 0
        let trailingConstraintConstant = contentView.constraint(byIdentifier: "trailingAnchor")?.constant ?? 0
        let leadingConstraintConstant = contentView.constraint(byIdentifier: "leadingAnchor")?.constant ?? 0

        collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width - trailingConstraintConstant - leadingConstraintConstant, height: 1)

        let size = collectionView.collectionViewLayout.collectionViewContentSize
        let newSize = CGSize(width: size.width, height: size.height + topConstraintConstant + bottomConstraintConstant)
        return newSize
    }
}

As a helper function to retrieve a constraint by identifier, I add the following extension:

extension UIView {
    func constraint(byIdentifier identifier: String) -> NSLayoutConstraint? {
        return constraints.first(where: { $0.identifier == identifier })
    }
}

NOTE: You will need to set the identifier on these constraints in your storyboard, or wherever they are being created. Unless they have a 0 constant, then it doesn't matter. Also, as in Pablo's response, you will need to use UICollectionViewFlowLayout as the layout for your collection view. Finally, make sure you link the collectionView IBOutlet to your storyboard.

With the custom table view cell above, I can now subclass it in any other table view cell that needs a collection view and have it implement the UICollectionViewDelegateFlowLayout and UICollectionViewDataSource protocols. Hope this is helpful to someone else!

Baucis answered 26/4, 2018 at 16:52 Comment(0)
K
13

I read through all the answers. This seems to serve all cases.

override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        collectionView.layoutIfNeeded()
        collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width , height: 1)
        return collectionView.collectionViewLayout.collectionViewContentSize
}
Kwangtung answered 14/12, 2018 at 16:3 Comment(1)
should be only accepted answer as it works perefectly with UICollectionview as UITableviewcell thanksNotecase
B
4

I was facing the same issue recently and I almost tried every solution in the answers, some of them worked and others didn't my main concern about @PabloRomeu approach is that if you have other contents in the cell (other than the collection view) you will have to calculate their heights and the heights of their constraints and return the result to get the auto layout right and I don't like to calculate things manually in my code. So here is the solution that worked fine for me without doing any manual calculations in my code.

in the cellForRow:atIndexPath of the table view I do the following:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //do dequeue stuff
    //initialize the the collection view data source with the data
    cell.frame = CGRect.zero
    cell.layoutIfNeeded()
    return cell
}

I think what happens here is that I force the tableview cell to adjust its height after the collection view height has been calculated. (after providing the collectionView date to the data source)

Bergius answered 14/6, 2018 at 3:15 Comment(0)
L
3

An alternative to Pablo Romeu's solution is to customise UICollectionView itself, rather than doing the work in table view cell.

The underlying problem is that by default a collection view has no intrinsic size and so cannot inform auto layout of the dimensions to use. You can remedy that by creating a custom subclass which does return a useful intrinsic size.

Create a subclass of UICollectionView and override the following methods

override func intrinsicContentSize() -> CGSize {
    self.layoutIfNeeded()

    var size = super.contentSize
    if size.width == 0 || size.height == 0 {
        // return a default size
        size = CGSize(width: 600, height:44)
    }

    return size
 }

override func reloadData() {
    super.reloadData()
    self.layoutIfNeeded()
    self.invalidateIntrinsicContentSize()
}

(You should also override the related methods: reloadSections, reloadItemsAtIndexPaths in a similar way to reloadData())

Calling layoutIfNeeded forces the collection view to recalculate the content size which can then be used as the new intrinsic size.

Also, you need to explicitly handle changes to the view size (e.g. on device rotation) in the table view controller

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
{
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
    dispatch_async(dispatch_get_main_queue()) {
        self.tableView.reloadData()
    }
}
Lach answered 19/7, 2016 at 1:10 Comment(1)
bro could you please help my problem #44650558 ?Adamsen
F
3

Easiest approach I've came up with, so far, Credits to @igor answer above,

In your tableviewcell class just insert this

override func layoutSubviews() {
    self.collectionViewOutlet.constant = self.postPoll.collectionViewLayout.collectionViewContentSize.height
}

and of course, change the collectionviewoutlet with your outlet in the cell's class

Fullmer answered 8/1, 2018 at 1:1 Comment(1)
The cell's height doesn't calculate properlyMaund
L
2

I would put a static method on the collection view class that will return a size based on the content it will have. Then use that method in the heightForRowAtIndexPath to return the proper size.

Also note that you can get some weird behavior when you embed these kinds of viewControllers. I did it once and had some weird memory issues I never worked out.

Lunseth answered 9/6, 2014 at 18:50 Comment(1)
For me, I was trying to embed a table view controller inside collection view controllers. Every time a cell is re-used, it ended up remembering some autolayout constraints I applied onto them. It was very fiddly and ultimately was a terrible idea. I think I will just use a single collection view instead.Walford
F
2

Maybe my variant will be useful; i've been deciding this task during last two hours. I don't pretend it's 100% correct or optimal, but my skill's very small yet and i'd like to hear comments from experts. Thank you. One important note: this works for static table - it's specified by my current work. So, all I use is viewWillLayoutSubviews of tableView. And a little bit more.

private var iconsCellHeight: CGFloat = 500 

func updateTable(table: UITableView, withDuration duration: NSTimeInterval) {
    UIView.animateWithDuration(duration, animations: { () -> Void in
        table.beginUpdates()
        table.endUpdates()
    })
}

override func viewWillLayoutSubviews() {
    if let iconsCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1)) as? CategoryCardIconsCell {
        let collectionViewContentHeight = iconsCell.iconsCollectionView.contentSize.height
        if collectionViewContentHeight + 17 != iconsCellHeight {
            iconsCellHeight = collectionViewContentHeight + 17
            updateTable(tableView, withDuration: 0.2)
        }
    }
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    switch (indexPath.section, indexPath.row) {
        case ...
        case (1,0):
            return iconsCellHeight
        default:
            return tableView.rowHeight
    }
}
  1. I know, that the collectionView is located in the first row of the second section;
  2. Let the height of the row is 17 p. bigger, than its content height;
  3. iconsCellHeight is a random number as the program starts (i know, that in the portrait form it has to be exactly 392, but it's not important). If the content of collectionView + 17 is not equal this number, so change its value. Next time in this situation the condition gives FALSE;
  4. After all update the tableView. In my case its the combination of two operations (for nice updating of extending rows);
  5. And of course, in the heightForRowAtIndexPath add one row to code.
Fleabite answered 25/5, 2016 at 10:50 Comment(0)
S
2

I get idea from @Igor post and invest my time to this for my project with swift

Just past this in your

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //do dequeue stuff
    cell.frame = tableView.bounds
    cell.layoutIfNeeded()
    cell.collectionView.reloadData()
    cell.collectionView.heightAnchor.constraint(equalToConstant: cell.collectionView.collectionViewLayout.collectionViewContentSize.height)
    cell.layoutIfNeeded()
    return cell
}

Addition: If you see your UICollectionView choppy when loading cells.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {       
  //do dequeue stuff
  cell.layer.shouldRasterize = true
  cell.layer.rasterizationScale = UIScreen.main.scale
  return cell
}
Sardonyx answered 1/5, 2019 at 21:27 Comment(1)
What will you do if cellForRowAt is called multiple times?Semiskilled
P
1

Pablo's solution did not work very well for me, I had strange visual effects (the collectionView not adjusting correctly).

What worked was to adjust the height constraint of the collectionView (as a NSLayoutConstraint) to the collectionView contentSize during layoutSubviews(). This is the method called when autolayout is applied to the cell.

// Constraint on the collectionView height in the storyboard. Priority set to 999.
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!


// Method called by autolayout to layout the subviews (including the collectionView).
// This is triggered with 'layoutIfNeeded()', or by the viewController
// (happens between 'viewWillLayoutSubviews()' and 'viewDidLayoutSubviews()'.
override func layoutSubviews() {

    collectionViewHeightConstraint.constant = collectionView.contentSize.height
    super.layoutSubviews()
}

// Call `layoutIfNeeded()` when you update your UI from the model to trigger 'layoutSubviews()'
private func updateUI() {
    layoutIfNeeded()
}
Pen answered 5/4, 2018 at 20:53 Comment(0)
C
0
func configure(data: [Strings]) {
        
        names = data
        contentView.layoutIfNeeded()
        collectionviewNames.reloadData()
    }

Short and sweet. Consider the above method in your tableViewCell class. You would probably call it from func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell after dequeing your cell. Before calling reloadData on your collection view, in your tableCell, you need to tell the collection view to lay out its subviews, if layout updates are pending.

Carboniferous answered 9/4, 2021 at 7:43 Comment(0)
K
-3

In your UITableViewDelegate:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ceil(itemCount/4.0f)*collectionViewCellHeight;
}

Substitute itemCount and CollectionViewCellHeight with the real values. If you have an array of arrays itemCount might be:

self.items[indexPath.row].count

Or whatever.

Klein answered 17/6, 2014 at 0:29 Comment(1)
I think the main question is to how to calculate collectionViewCellHeight before it renders.Cranky
S
-3

1.Create dummy cell.
2.Use collectionViewContentSize method on UICollectionViewLayout of UICollectionView using current data.

Samadhi answered 18/6, 2014 at 10:26 Comment(3)
It should be the best answer... since there is no possibility to set the height of cell with 'uicollectionview' without putting the content to the dummy cell, get height, and then set it again to the proper cellMalayoindonesian
how do i use that method?Parvenu
Add an example.Maund
P
-5

You can calculate the height of the collection based on its properties like itemSize, sectionInset, minimumLineSpacing, minimumInteritemSpacing, if your collectionViewCell has the border of a rule.

Pyongyang answered 30/6, 2015 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.