I'm having trouble to scrolling to bottom, I tried other solutions but with no success.
I'm using IGLiskit
Here's the error:
attempt to scroll to invalid index path
Here's the code:
func initMessages() {
DataService.call.retrieveMessages(roomID: room.id ?? "") { (success, error, messages) in
if !success {
print("error", error!.localizedDescription)
} else {
guard let messages = messages else {return}
self.messages = messages
DispatchQueue.main.async {
self.adapter.performUpdates(animated: true, completion: nil)
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
}
}
}
do you have 2 sections in collectionview?, it this yes ignore my answer, i hope the problem is you are trying to acces a section 1, you just have the section 0 available, try to change this code:
func initMessages() {
DataService.call.retrieveMessages(roomID: room.id ?? "") { (success, error, messages) in
if !success {
print("error", error!.localizedDescription)
} else {
guard let messages = messages else {return}
self.messages = messages
DispatchQueue.main.async {
self.adapter.performUpdates(animated: true, completion: nil)
// Here in section
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
}
}
}
EDIT: ok, if the section didn't work try this extension:
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)
}
}
usage:
collectionView.scrollToLast()