UICollectionView:设置新布局和目标内容偏移量

Att*_*a H 5 cocoa-touch objective-c ios uicollectionview uicollectionviewlayout

我有一个UICollectionView和两个子类UICollectionViewFlowLayout。选择单元格时,我调用setCollectionViewLayout:animated:在布局之间切换。过渡完成后,选定的单元格居中,这很好。

可以在不实际选择单元格的情况下完成相同的居中行为吗?我尝试调用setContentOffset:animated:不同的方法但没有成功。或者,我可以contentOffset为要显示的布局指定一个自定义的吗?

更清楚地说,我想在不修改单元格selected属性的情况下拥有这样的东西:在此处输入图片说明

编辑#1

这是我已经拥有的:

[self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self.collectionView setCollectionViewLayout:layout animated:YES];
Run Code Online (Sandbox Code Playgroud)

看起来不错:https : //www.dropbox.com/s/9u6cnwwdbe9vss0/17249646-0.mov


但如果我跳过selectItemAtIndexPath

[self.collectionView setCollectionViewLayout:layout animated:YES];
[self.collectionView scrollRectToVisible:targetFrame animated:YES];
Run Code Online (Sandbox Code Playgroud)

这不是很好(一种挥手动画):https : //www.dropbox.com/s/s3u2eqq16tmex1v/17249646-1.mov

Tim*_*ose 0

编辑(进一步澄清后更改答案)

我在这里对表视图做了类似的事情。基本上,您调用scrollRectToVisible:animated:计算一个矩形,将您的滚动视图放置在您希望其结束的位置。为了精确定位,我认为你只需要计算一个与你的视图大小相同的矩形。请注意,如果内容大小要更改,则应按照预期的最终内容大小计算矩形。

原答案

layoutAttributesForElementsInRect:rect您可以通过覆盖类似以下内容来修改超类生成的布局:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

您还需要layoutAttributesForItemAtIndexPath使用类似的逻辑进行覆盖。下一步是当您希望发生更改时使布局无效或替换您的布局。您还需要传递一些信息。布局需要知道要做什么,因此您可以向其传递相关数据或扩展UICollectionViewDelegateFlowLayout1