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

标签 ios objective-c cocoa-touch uicollectionview uicollectionviewlayout

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

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

更清楚地说,我希望在不修改单元格的 selected 属性的情况下拥有这样的东西:enter image description here

编辑#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/

相关文章:

iOS 钥匙串(keychain) :strange behavior while setting and getting data in/out the keychain

ios - Apple 的 doCipher 示例代码中的不良做法 :key:context:padding method

iphone - 如何在 iphone 的单个 View 上显示多个视频

ios - 检查 NSString 的特定日期格式

iPhone - 在 UIViewController 中处理触摸滑动

ios - 设置了与objectAtIndexes无关的索引

ios - 渐变 alpha 在 drawRect 中不起作用

ios - 无法从 Objective-C 通用框架引用 Swift 通用框架的类和方法

objective-c - 使用 Instagram API 进行身份验证时,gtm-oauth2 在 Mac OSX 上崩溃

objective-c - 将 JSON 结果解析为 NSString 或 RestKit 中类似的 "primitive"数据类型