![](/img/trans.png)
[英]How to scroll to the bottom of a CollectionView when the user taps the InputAccessoryView
[英]How to Scroll CollectionView to bottom Programmatically
我使用此代碼滾動集合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]'
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
你將收到與你有相同的錯誤
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)
}
}
您還可以使用contentOffset
將CollectionView
為Bottom
這是一個例子
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)
}
func scrollToItem(at: IndexPath, at: UICollectionViewScrollPosition, animated: Bool)
可以滾動集合視圖內容,直到指定的項目可見。 如果item不可見,則會因為未捕獲的異常'NSRangeException'而終止應用程序,例如終止應用程序,原因:'...
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)
}
}
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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.