我有一个 UICollectionView
和 UICollectionViewFlowLayout
的两个子类。选择一个单元格后,我调用 setCollectionViewLayout:animated:
在布局之间切换。过渡完成后,所选单元格居中,这很好。
是否可以在不实际选择单元格的情况下完成相同的居中行为?我尝试用不同的方法调用 setContentOffset:animated:
但没有成功。或者,我可以为要显示的布局指定一个自定义的 contentOffset
吗?
更清楚地说,我希望在不修改单元格的 selected
属性的情况下拥有这样的东西:
编辑#1
这是我已经拥有的:
[self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self.collectionView setCollectionViewLayout:layout animated:YES];
看起来不错:https://www.dropbox.com/s/9u6cnwwdbe9vss0/17249646-0.mov
但是如果我跳过 selectItemAtIndexPath
:
[self.collectionView setCollectionViewLayout:layout animated:YES];
[self.collectionView scrollRectToVisible:targetFrame animated:YES];
这不是很好(一种挥手动画):https://www.dropbox.com/s/s3u2eqq16tmex1v/17249646-1.mov
最佳答案
编辑(进一步澄清后更改答案)
我对 TableView 做了类似的事情 here .基本上,您调用 scrollRectToVisible:animated:
计算出一个矩形,它将 ScrollView 定位在您希望它结束的位置。对于精确定位,我认为你只需要计算一个与你的 View 大小相同的矩形。请注意,如果内容大小将发生变化,则应以预期的最终内容大小计算矩形。
原始答案
您可以通过使用如下内容覆盖 layoutAttributesForElementsInRect:rect
来修改父类(super class)生成的布局:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *poses = [super layoutAttributesForElementsInRect:rect];
if (<test whether we want to modify poses>) {
UICollectionViewLayoutAttributes *pose = poses[<index of pose to be modified>];
pose.frame = <some other frame>;//modify the frame, for example
}
return poses;
}
您还需要使用类似的逻辑覆盖 layoutAttributesForItemAtIndexPath
。下一步是在您希望更改发生时使您的布局无效或替换。您还需要传递一些信息。布局需要知道要做什么,因此您可以将相关数据传递给它或扩展 UICollectionViewDelegateFlowLayout1
。
关于ios - UICollectionView:设置新布局和目标内容偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17249646/