Thanks to @urvashikoladiya's help
For those who might be interested in the solution, I need to dispatch the scrollToItem function's call because my UICollectionView child cell is already animating so I have to be sure the animation is finish before asking the scroll position to top.
There might be a more elegant way to do it, but I haven't found
class MyCollectionViewCell: UICollectionViewCell,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
if let nextIndexPath = context.nextFocusedIndexPath {
delegate?.selectedRow(cell: self)
}
}
class MainCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout, CollectionViewCellDelegate {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionViewCell
cell.delegate = self
return cell
}
override func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool {
return false
}
func selectedRow(cell: MyCollectionViewCell) {
if let indexPath = collectionView.indexPath(for: cell) {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) {
self.collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
}
}
}
}