IOS: Weird animation on UICollectionView orientation
The cell size of UICollectionView is the full screen size. And the user can swipe horizontally. The problem is during the orientation, I can see the next or previous cell. (Attached screenshot here. the red cell is current one, the purple cell is the next cell.) And sometimes after orientation, collection view will scroll to wrong cell index. (I use scrollToItemAtIndexPath to force change it back to correct one...)
I tried two ways to solve this problem.
1) use flow layout:
- (UICollectionViewLayoutAttributes*)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath
{
// after orientation, scroll to the correct position.
UICollectionViewLayoutAttributes* attr = [super initialLayoutAttributesForAppearingItemAtIndexPath:itemIndexPath];
[self.collectionView scrollToItemAtIndexPath:itemIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
return attr;
}
- (void)prepareForAnimatedBoundsChange:(CGRect)oldBounds
{
NSLog(@"%@ prepare animated bounds change", self);
[super prepareForAnimatedBoundsChange:oldBounds];
}
- (void)finalizeAnimatedBoundsChange
{
NSLog(@"%@ finalize animated bounds change", self);
[super finalizeAnimatedBoundsChange];
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
CGRect oldBounds = self.collectionView.bounds;
if (!CGSizeEqualToSize(oldBounds.size, newBounds.size)) {
if(oldBounds.size.width > newBounds.size.width)
{
// vertical cell size
self.itemSize = CGSizeMake(768, 968);
}
else{
// horizontal cell size
self.itemSize = CGSizeMake(1024, 712);
}
NSLog(@"%@ should invalidate layout", self);
return YES;
}
return NO;
}
2) use in delegate call
// used in will rotate and did rotate, but both does not work well...
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// do invalidate layout
[self.CollectionView.collectionViewLayout invalidateLayout];
}
// then change the cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
UIInterfaceOrientation o = [[UIApplication sharedApplication] statusBarOrientation];
if (UIInterfaceOrientationIsPortrait(o)) {
return CGSizeMake(768, 968);
} else {
return CGSizeMake(1024, 712);
}
}
I do not want to use fake image to hide layout changes during animation. Thanks!! :)
链接地址: http://www.djcxy.com/p/84166.html