Reputation: 16426
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:
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?
Upvotes: 1
Views: 467
Reputation: 1152
In viewDidLoad, add observer for collection view,
collectionView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.Old.union(NSKeyValueObservingOptions.New), context: self)
Now, overrider observe value for keypath for controlling collection view reload completion handler through KVO.
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
{
// You will get here when the reloadData finished
}
Now, in view Will Disappear remove observer that was set for collection view.
override func viewWillDisappear(_ animated: Bool) {
{
// remove collection view observer
}
Same logic will be applied for tableview in order to get fully visible tableview cell containing collection view inside it.
Upvotes: 0