我使用此代码滚动集合View:
let section = (self.collectionView?.numberOfSections)! - 1;
let item = (self.collectionView?.numberOfItems(inSection: section))! - 1;
let lastIndexPath = IndexPath(item: item, section: section);
self.collectionView?.scrollToItem(at: lastIndexPath, at: .bottom, animated: true);
但我得到错误:
*由于未捕获的异常'NSRangeException'终止应用程序,原因:'* - [__ NSArrayM objectAtIndex:]:索引1超出边界[0 .. 0]'
答案 0 :(得分:7)
let lastItemIndex = NSIndexPath(forItem: data.count - 1, inSection: 0)
collectionView?.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: .Bottom, animated: true)
不要忘记:
- atScrollPosition:.Bottom
- 并且您需要检查data.count > 0
因为if data.count == 0
您将收到与您相同的错误
答案 1 :(得分:5)
Swift 4 +
extension UICollectionView {
func scrollToLast() {
guard numberOfSections > 0 else {
return
}
let lastSection = numberOfSections - 1
guard numberOfItems(inSection: lastSection) > 0 else {
return
}
let lastItemIndexPath = IndexPath(item: numberOfItems(inSection: lastSection) - 1,
section: lastSection)
scrollToItem(at: lastItemIndexPath, at: .bottom, animated: true)
}
}
答案 2 :(得分:4)
您可以使用CollectionView
contentOffset
设置为底部动画
这是一个例子
let contentHeight: CGFloat = myCollectionView.contentSize.height
let heightAfterInserts: CGFloat = myCollectionView.frame.size.height - (myCollectionView.contentInset.top + myCollectionView.contentInset.bottom)
if contentHeight > heightAfterInserts {
myCollectionView.setContentOffset(CGPoint(x: 0, y: myCollectionView.contentSize.height - myCollectionView.frame.size.height), animated: true)
}
答案 3 :(得分:0)
func scrollToItem(at: IndexPath, at: UICollectionViewScrollPosition, animated: Bool)
可以滚动集合视图内容,直到指定的项目可见。如果项目不可见,则会因为未捕获的异常而导致应用终止,例如:NSRangeException'原因:' ...
答案 4 :(得分:0)
var xItem:Int = 0
var currentIndex:NSIndexPath!
@IBOutlet weak var rateCollection: UICollectionView!
@IBAction func btnNextTapped(_ sender: UIButton)
{
xItem = xItem+1
if xItem != arrayRateModel.count
{
currentIndex = NSIndexPath(item: xItem, section: 0)
rateCollection.scrollToItem(at: currentIndex as IndexPath, at: .centeredHorizontally, animated: true)
}
}
答案 5 :(得分:0)
NSInteger noOfsections = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
NSInteger noOFItems = [self collectionView:self.collectionView numberOfItemsInSection:noOfsections] - 1;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:noOFItems inSection:noOfsections];
[self.collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];