Autosizing UICollectionView cell embedded in UITableView not working

痞子三分冷 提交于 2019-12-24 19:32:53

问题


I have spent a few day's now trying out things suggested on various SO posts but have not been able to figure this out. I'm probably looking right at the issue!

I am making a switch over from Android to iOS and seem to be having some trouble with autolayout. Specifically, getting the UICollectionView to resize to the height of its content. Each collection view can have a different cell size based on its content but the cell size will be the same for each item on a given row.

The UICollectionView is nested inside a UITableViewCell. The UITableViewCells appear to be resizing to its content height correctly and looking at the Debug View Hierarrchy the issue seems to be the UICollectionView.

I have created a mini demo and put it on this github (link below). I have thrown in a bunch of test data so the bottom part of the ViewController VC is a bit messy. The demo just illistrates how each row can have different content size. There can be several table rows of the same style.

NOTE: I had to add the following line to CategoryRowCell.swift in order for me to get the below screen shots. Without this line the UICollectionView height becomes 0!

...
collectionView.heightAnchor.constraint(equalToConstant: 250)
...

GitHub link

So here is what it looks like right now..

scrolled down

Notice the gaps at the top and bottom of the horizontal lists. Here is what i am expecting..

Here is part of the debug view hierarchy. You will see that the collection view already has top and bottom margins (good), but the red lines show the excess height being applied to the collection view. The green line indicates the height i am expecting. I am wanted the collection view to have a height of its content.


回答1:


I think it would be better to do it the other way around, having the UICollectionView as the parent and UITableView as the child. Since the first is more flexible and customizable.

Anyway for your case I think you need to take a look at two things:

1- To have a better control of the cell size you can use this func for UICollectionView:

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

  // The desired size based on the value at that row (the name for example)

  if objects[indexPath.row].name == "some condition" {
    return CGSize(width: 150, height: 50)
  }
  else {
    return CGSize(width: UIScreen.main.bounds.width, height: 75)
  }


}

2- The size inspector values for the UICollectionView and UITableView (you might have some extra spacing in one of them)



来源:https://stackoverflow.com/questions/55000840/autosizing-uicollectionview-cell-embedded-in-uitableview-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!