检查`UICollectionView`索引路径是否有效?

时间:2016-08-05 05:21:17

标签: ios objective-c uicollectionview

我正在尝试滚动到UICollectionView中的指定索引路径:

if ([self collectionView:self.collectionView numberOfItemsInSection:0] > self.activeIndexPath.row && self.activeIndexPath.row > 0)
    [self.collectionView scrollToItemAtIndexPath:self.activeIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];

但是我不断遇到这个错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: <NSIndexPath: 0x1ff80a30> {length = 2, path = 0 - 40}

如何在滚动之前验证索引路径?我的收藏视图只有1个部分。

2 个答案:

答案 0 :(得分:2)

检查并验证要传递的indexPath。

如果没问题,请尝试记录collectionView的numberofItemsInSection。

然后,尝试重新加载collectionView,然后滚动到indexPath,如:

[self.collectionView reloadData];

答案 1 :(得分:0)

首先,您需要获取collectionView的indexPath,我的代码为 -

目标C代码 -

- (UIView *)superviewWithClassName:(NSString *)className fromView:(UIView *)view
{
    while (view)
    {
        if ([NSStringFromClass([view class]) isEqualToString:className])
        {
            return view;
        }
        view = view.superview;
    }
    return nil;
}

然后我从按钮处理程序中调用它,如下所示: -

- (IBAction)buttonClicked:(id)sender
{
    UIButton *button = (UIButton *)sender;
    UICollectionViewCell *cell = (UICollectionViewCell *)
                                [self superviewWithClassName:@"UICollectionViewCell"
                                fromView:button];
    if (cell)
    {
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
        // do whatever action you need with the indexPath...
    }
}

SWIFT 2.x代码 -

func superviewWithClassName(className:String, fromView view:UIView?) -> UIView? {
    guard let classType = NSClassFromString(className) else {
        return nil
    }
    var v:UIView? = view
    while (v != nil) {
        if v!.isKindOfClass(classType) {
            return v
        }
        v = v!.superview
    }
    return nil
}

您可以在CollectionView页面上的任何位置访问indexPath,如下所示 -

guard let cell = UIView.superviewWithClassName("UICollectionViewCell", fromView: sender as? UIView) as? UITableViewCell else {return}