我有一个照片库视图使用UICollectionView与UICollectionViewFlowLayout,它有pagingEnabled和水平滚动显示一次只有一个视图.
工作很好,直到我尝试旋转它
当我旋转设备时,willRotatetoInterfaceOrientation:duration:我更新collectionView.contentOffset,使其保持在正确的项目上,并调整currentCell的大小,使其动画化到新的维度.问题在于这两个状态之间的动画,“上一个”方向从左上角动画,并且转向视图中的其他单元格.我做错了什么,从屏幕上动画的视图是FUBAR?
这是什么样的行动:
http://www.smugmug.com/gallery/n-3F9kD/i-BwzRzRf/A(忽略片断的视频,那是Quicktime的故障:p)
这是我的意志动画重新开始时间:持续时间:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration]; // Update the flowLayout's size to the new orientation's size UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout; if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) { flow.itemSize = CGSizeMake(self.collectionView.frame.size.width,self.collectionView.frame.size.height); } else { flow.itemSize = CGSizeMake(self.collectionView.frame.size.width,self.collectionView.frame.size.height); } self.collectionView.collectionViewLayout = flow; [self.collectionView.collectionViewLayout invalidateLayout]; // Get the currently visible cell PreviewCellView *currentCell = (PreviewCellView*)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0]]; // Resize the currently index to the new flow's itemSize CGRect frame = currentCell.frame; frame.size = flow.itemSize; currentCell.frame = frame; // Keep the collection view centered by updating the content offset CGPoint newContentOffset = CGPointMake(_currentIndex * frame.size.width,0); self.collectionView.contentOffset = newContentOffset; }
据我所知,我找不到任何示例代码,说明如何使“照片库”样式集合视图正常旋转.
解决方法
我一直在努力争取一段时间,直到我至少发现了这个“化妆品解决方案”:
在旋转期间,在collectionView的顶部添加一个全屏UIImageView与当前图像(以及正确的自动布局约束集).像这样:
-(void)willRotatetoInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration: (NSTimeInterval)duration { [self.collectionView.collectionViewLayout invalidateLayout]; // show a UIImageView with the current image on top of the collectionView // to cover the ugly animation self.imageViewOnTopOfCollectionView.image = [self imageForItemAtIndexPath:self.currentIndexPath]; self.imageViewOnTopOfCollectionView.hidden = NO; // show a centered,very large 'fakeBackground' view on top of // the UICollectionView,but below the UIImageView self.fakeBackground.hidden = NO; } -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { // ... set correct contentOffset // hide the fake views again self.imageViewOnTopOfCollectionView.hidden = YES; self.fakeBackground.hidden = YES; }
一个大的’fakeBackground’将是一个额外的改进,以防止部分丑视图动画在此ImageViews框架旋转之前可见.例如.一个超大(大于视图的所有维度的界限)UIView具有与collectionView相同的背景颜色,z-Index位于collectionView和imageView之间.