我有点困惑,我无法解决一件非常简单的事情。
我的CollectionView有50个单元格,我想使用“下一步”按钮和“后退”按钮在这些单元格之间来回滚动。我知道scrollToItemAtIndexPath方法,但是在找到正确的IndexPath时遇到问题。有人可以帮助我吗?
这是我的代码:
// My personal method
-(void)scrollYearAtIndex:(NSInteger)index {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
[_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
// Show Next Items
-(void)didScrollNextYear {
[self scrollYearAtIndex:????];
}
// Show Previous Items
-(void)didScrollPreviousYear {
[self scrollYearAtIndex:????];
}
答案 0 :(得分:1)
let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems()
let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath
这将为您提供当前选定的索引路径。在didScrollNextYear
方法中,将indexPath.row加1。在didScrollPreviousYear
中,将indexPath.row减1。
示例代码:
// Show Next Items -(void)didScrollNextYear { let indexPaths : NSArray = self.collectionView!.indexPathsForSelectedItems() let indexPath : NSIndexPath = indexPaths[0] as NSIndexPath [self scrollYearAtIndex: indexPath.row+1]; }
答案 1 :(得分:1)
我在Swift
中给出了答案。您可以在Objective-C
中编写相同的逻辑。
要获取下一个indexPath
,请获取排序后的last
数组的indexPath
indexPathsForVisibleItems
并加1。
要获取先前的indexPath
,请获取排序后的first
数组的indexPath
indexPathsForVisibleItems
并递减1。
func didScrollNextYear() {
if let index = self.collectionView.indexPathsForVisibleItems.sorted().last?.row {
let nextIndex = index+1
if nextIndex < self.collectionView.numberOfItems(inSection: 0) {
self.collectionView.scrollToItem(at: IndexPath(row: nextIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
func didScrollPreviousYear() {
if let index = self.collectionView.indexPathsForVisibleItems.sorted().first?.row {
let previousIndex = index-1
if previousIndex >= 0 {
self.collectionView.scrollToItem(at: IndexPath(row: previousIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
答案 2 :(得分:0)
调用此功能可进入下一个和上一个按钮IBAction
func scrollToNextCell()
{
let collectionView = yourCollectionView
let cellSize = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
let contentOffset = collectionView!.contentOffset;
collectionView!.scrollRectToVisible(CGRect(x: contentOffset.x + cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true)
}
func scrollToPreviousCell()
{
let collectionView = yourCollectionView
let cellSize = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
let contentOffset = collectionView!.contentOffset;
collectionView!.scrollRectToVisible(CGRect(x: contentOffset.x - cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true)
}