我有一个从故事板连接的按钮,我想按下时将我的水平滚动集合视图向右滚动一个项目。这是我提出的代码:
- (IBAction)rightButton:(id)sender {
NSIndexPath *indexPath = [self.collectionView indexPathsForSelectedItems];
NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
[self.collectionView scrollToItemAtIndexPath:newIndexPath
atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
animated:YES];
}
但是,这会导致崩溃,错误
-[__NSArrayI row]: unrecognized selector sent to instance 0x178232540
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI row]: unrecognized selector sent to instance 0x178232540'
我怀疑问题是这个代码更适用于TableView,它不喜欢那里的部分停放。
有人可以帮我解决这个问题并弄清楚我为什么会收到错误吗?有更好的方法吗?
由于
答案 0 :(得分:1)
indexPathsForSelectedItems
方法名称中包含额外的s
,Paths
不是Path
,这表示它返回NSArray
个索引路径,而不是单个索引路径。因此,解决方案是改变这些行
NSIndexPath *indexPath = [self.collectionView indexPathsForSelectedItems];
NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
到这个
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
if ( indexPaths.count > 0 )
{
NSIndexPath *oldIndexPath = indexPaths[0];
NSInteger oldRow = oldIndexPath.row;
newIndexPath = [NSIndexPath indexPathForRow:oldRow + 1 inSection:oldIndexPath.section];
}