I have a problem similar to this one:

or like this:
or like this:
Using this code:
DemoTableViewCell
class DemoTableViewCell: UITableViewCell {
@IBOutlet var label: UILabel!
@IBOutlet var myView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
myView.layer.cornerRadius = 8
myView.layer.shadowOffset = CGSize(width: 0, height: 3)
myView.layer.shadowRadius = 3
myView.layer.shadowOpacity = 0.5
}
}
DemoTableViewController
class DemoTableViewController: UITableViewController {
let myData: [String] = [
"Single Line",
"A longer string which will wrap in Portrait Orientation",
"This string is long enough that the text will need to word-wrap (on an iPhone 8) whether in Portrait Orientation or Landscape Orientation",
"Another Single Line",
]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Demo Table"
view.backgroundColor = .systemBackground
tableView.register(UINib(nibName: "DemoTableViewCell", bundle: nil), forCellReuseIdentifier: "c")
tableView.tableFooterView = UIView()
tableView.separatorStyle = .none
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath) as! DemoTableViewCell
cell.label.text = myData[indexPath.row]
return cell
}
}
At run-time, we'll get this:
and note that the layout is automatically handled when the view size changes:
So, a few issues with your designs...
First, trying to use a UICollectionView in that way is inherently problematic. Collection views are designed to layout their cells and scroll when there are more cells than will fit.
By using the opposite approach - get the size needed to display all the cells and then resize the collection view, all while embedding it in a table view cell - is a rather complex task.
In order for the collection view to determine its contentSize.height:
- it needs to be given a width
- it needs to get the cell section and items count
- it needs to get the sizes of the cells (particularly if they are not a fixed size)
- it needs to then layout the cells
- and... that's an async process
- and... in this case, the collection view doesn't get its width until the table view has laid out its cell
Trying to handle the timing on all of that is very difficult.
Now, since you're throwing away many of the benefits of a collection view (scrolling, cell reuse, etc), and you're likely using a small number of "items" (if you're trying to do this with a couple hundred cells you probably need to re-think your UI design) you're almost certainly better off writing code to layout the views yourself.
For a little more detail and code examples, I put up a demo project here: https://github.com/DonMag/TagsTableExample




