我有一个collectionView,它是屏幕的宽度,我需要它切换到下一部分,而不是从右边的视图中检索该视图。我碰巧用此代码将其工作1次,然后停止工作,尽管程序可以正常工作且没有错误。
@objc func RightButtonClick(button1: UIButton) {
let indexOfCell = button1.tag
let visibleItems: NSArray = self.CollectionView2.indexPathsForVisibleItems as NSArray
let currentItem: IndexPath = visibleItems.object(at: 0) as! IndexPath
let nextItem: IndexPath = IndexPath(item: currentItem.item + indexOfCell, section: 0)
if nextItem.row == CollectionView2.numberOfSections {
self.CollectionView2.scrollToItem(at: nextItem, at: .left, animated: true)
}
}
}
您的nextItem设置为第0部分,因此您将永远不会进入下一部分。试试这个:
@objc func RightButtonClick() {
let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray
guard let currentItem: IndexPath = visibleItems.object(at: 0) as? IndexPath else { return }
print(currentItem.section)
print(collectionView.numberOfSections)
if collectionView.numberOfSections > currentItem.section + 1 {
let nextSection: IndexPath = IndexPath(item: 0, section: currentItem.section + 1)
self.collectionView.scrollToItem(at: nextSection, at: .left, animated: true)
}
}
注意:您不需要按钮标签即可执行类似的操作,因此将其删除。
如果您只有一个部分,而您要转到该部分的下一项,请尝试以下操作:
@objc func RightButtonClick() {
let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray
guard let currentItem: IndexPath = visibleItems.object(at: 0) as? IndexPath else { return }
print(currentItem.section)
print(collectionView.numberOfSections)
if collectionView.numberOfItems(inSection: 0) > currentItem.row + 1 {
let nextItem: IndexPath = IndexPath(item: currentItem.row + 1, section: 0)
self.collectionView.scrollToItem(at: nextItem, at: .centeredHorizontally, animated: true)
}
}