ios - 从整数(int或NSInteger)到UICollectionView的NSIndexPath *

时间:2014-10-31 13:12:32

标签: ios objective-c iphone uicollectionview nsindexpath

我正在尝试调用collectionView...scrollToItemAtIndexPathUICollectionView滚动到第i个单元格,其中i是元素的索引。我的集合视图只有一个部分,当我去另一个部分时,我总是调用dataArray[indexPath.item]来获取indexPath中元素的数据。但是,我无法从整数中获取indexPath。

[NSIndexPath indexPathForRow:]仅适用于UITableView

[NSIndexPath indexPathWithIndex:]不会返回带有

部分的NSIndexPath

[NSIndexPath indexPathForItem:inSection:0]返回0长度的路径,当用于获取[collectionView cellAtIndexPath:]的单元格时返回nil

我知道如何获得一个有效的索引路径,然后我可以使用它来滚动UICollectionView?假设我只有数据数组的NSInteger索引。感谢。

更新代码:

NSIndexPath* pathToCell = [NSIndexPath indexPathForItem:curIndex inSection:0];
    CustomCollectionViewCell* updatedCell = (CustomCollectionViewCell*)[self collectionView:self.collection cellForItemAtIndexPath:pathToCell];
    selectedContent = updatedCell.cellContentView;

    // scroll to cell and recenter cover on it
    [self.collection scrollToItemAtIndexPath:pathToCell atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];

然后我使用单元格的位置重新定位其顶部的“封面”视图:

// Animate
CGPoint coverCenter = [childView convertPoint:selectedContent.center toView:parentView];

coverSelectDummy.center = coverCenter;
coverSelectDummy.imageView.image = selectedContent.imageView.image;
coverSelectDummy.imageLabel.text = selectedContent.imageLabel.text;
coverSelectDummy.alpha = 1.0;
coverSelectDummy.transform = CGAffineTransformIdentity;
coverSelectDummy.hidden = NO;

[self.view bringSubviewToFront:coverSelectDummy];

[UIView transitionWithView:coverSelectDummy duration:0.1f options: UIViewAnimationOptionCurveLinear animations:^(void)
 {
     coverSelectDummy.alpha = 1.0;
     coverSelectDummy.transform = CGAffineTransformMakeScale(1.2, 1.2);

 }
                completion:^(BOOL finished)
 {
     // .... processing ....
 }];

1 个答案:

答案 0 :(得分:3)

如果单元格不可见(documentation),则

cellForItemAtIndexPath:返回nil。因此,如果您想要滚动到当前不在屏幕上的项目,那将无效。如果我理解正确你只想在某个地方滚动,那么我认为你甚至不需要担心这种方法。

您应该使用创建NSIndexPath对象 indexPathForItem:inSection:,然后使用scrollToItemAtIndexPath:atScrollPosition:animated:

滚动到该索引路径

因此,假设集合视图是有问题的View Controller的属性,并且您有一个滚动位置变量:

NSInteger itemToScrollTo = 10;
NSIndexPath *indexPathToScrollTo = [NSIndexPath indexPathForItem:itemToScrollTo inSection:0];
[self.collectionView scrollToItemAtIndexPath:indexPathToScrollTo atScrollPosition:scrollPosition animated:YES];