I have a UICollectionView inside a UITableViewCell.
I am setting the UITableViewCell row height to be dynamic:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
My UICollectionView has a variable number of items:
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return items.count
}
Now here is the sequence of events that is causing me headache:
- UITableView calls delegate cellForRowAt and dequeues a UITableViewCell with dynamic height
- In the NEXT loop cycle, the UICollectionView inside the UITableViewCell calls on its delegates numberOfItemsInSection and cellForItemAt to determine the UICollectionView contentSize.
- Now it's too late since the UITableViewCell has already been dynamically sized with a UICollectionView that has no cells, and so the UITablewViewCell height is too short and does NOT fit the UICollectionView properly.
I have found an ugly work around by reloading the UITableView but I don't like this approach at all:
private func reloadCell() {
let when = DispatchTime.now()
DispatchQueue.main.asyncAfter(deadline: when) {
if let indexPath = self.chatViewController?.chatTableView.indexPath(for: self) {
self.tableView.reloadRows(at: [indexPath], with: .none)
}
}
}
My question is if I can force the UICollectionView to reload and call it's delegates immediately so that the UITableViewCell height can be computed by the autolayout engine correctly?