2016-08-05 62 views
0

我试图滚动到指定索引路径在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

检查和验证您正在传递indexPath。

如果可以,请尝试为您的collectionView记录numberofItemsInSection。

然后,尝试滚动到indexPath像以前一样重装的CollectionView:

[self.collectionView reloadData]; 
+1

似乎第一次重新加载数据后,开始工作,我会接受,如果在接下来的几天崩溃不会再出现 – Cbas

+0

@Cbas - 当然!高兴地帮助:) –

+0

@Cbas - 您的问题是否已解决?请接受答案,如果它已经:) –

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 
} 

您可以从任何地方,你想在你访问indexPath的CollectionView页面这样的 -

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

我已经有了索引路径,不知道如何这有助于 – Cbas