What I want to achieve is very simple: each time user focuses a collection view cell, I want to make the focused cell horizontally centered. It seems like my current approach doesn't work at all.
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
guard collectionView === self.categoryCollectionView else {
return
}
guard let indexPath = context.nextFocusedIndexPath else {
return
}
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
}
What is odd is that collection view ignores any attempt to scroll anywhere. For testing purposes, I changed index path to the last item's index path in collection view, but it works only when collection view appears for the first time.
The trick is to make sure you have set UICollectionView scrollEnabled = false.
override func didUpdateFocusInContext(context: UIFocusUpdateContext,
withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if let focusedView = context.nextFocusedView as? UITableViewCell {
collectionView.scrollEnabled = false
let indexPath = collectionView.indexPathForCell(focusedView)!
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With