滚动到特定的集合视图标题(不是单元格)

时间:2014-04-02 12:20:25

标签: ios objective-c uicollectionview

我有一个带有索引视图的collectionview(一个自定义的,因为apple只适用于UITableViews),这个索引视图是一个UIControl子类,在触发“value changed”事件时调用一个方法。 显然,被调用的方法将集合视图滚动到与被触摸的字母相关联的部分。 所以,这是我对这个方法的实现:

- (IBAction)indexViewValueChanged:(id)sender
{
    NSIndexPath * indexPath = [NSIndexPath indexPathForItem:0 inSection: [sender currentIndex]];

    [collectionView scrollToItemAtIndexPath: indexPath atScrollPosition: UICollectionViewScrollPositionTop animated: NO];

    collectionView.contentOffset = CGPointMake(collectionView.contentOffset.x, MAX(collectionView.contentOffset.y - [(UICollectionViewFlowLayout *)[collectionView collectionViewLayout] headerReferenceSize].height, 0));
}

问题是由于contentOffset调整(最后一行),某些情况不起作用。 例如,如果相关部分下面的内容小于collectionView,则在scrollToItemAtIndexPath:atScrollPosition:animated:call之后,标题将不会位于屏幕顶部,这是正常的,但我想阻止contentOffset调整这是在下一行代码中生成的。 我的问题是我不知道如何确定标题已经可见并避免此contentOffset调整。

我在接受任何想法:)

1 个答案:

答案 0 :(得分:0)

由于每个部分只能有一个标题,请滚动到NSIndexPath项目值为0的第一个项目,而section值是目标部分的编号。

有几种搜索特定的索引路径值。这是一种方式:

[self.collectionView.visibleCells indexOfObjectPassingTest:^BOOL(__kindof UICollectionViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        BOOL result = ([self.collectionView indexPathForCell:obj].item == 0 && [self.collectionView indexPathForCell:obj].section == 2);
            // Scroll to item at [self.collectionView indexPathForCell:obj]
        stop = &result;
        return result;
    }];