我有一个UICollectionView来显示聊天消息。在开始时,我将现有消息加载到collectionView,并使用此方法将collectionView向下滚动到最后一条消息:
- (void)scrollToLastMessageAnimated:(BOOL)animated;
{
if (_messages.count == 0) { return; }
NSUInteger indexOfLastSection = _messagesBySections.count - 1;
NSInteger indexOfMessageInLastSection = [_messagesBySections[indexOfLastSection] count] - 1;
NSIndexPath *path = [NSIndexPath indexPathForItem:indexOfMessageInLastSection
inSection:indexOfLastSection];
[_collectionView scrollToItemAtIndexPath:path
atScrollPosition:UICollectionViewScrollPositionCenteredVertically
animated:animated];
}
当我在viewDidAppear:方法中调用它而不是在viewWillAppear:方法中调用它时,它才有效。如何在没有动画的情况下向下滚动?
答案 0 :(得分:8)
这是......
NSInteger section = [self.collectionView numberOfSections] - 1;
NSInteger item = [self.collectionView numberOfItemsInSection:section] - 1;
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:section];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:(UICollectionViewScrollPositionBottom) animated:YES];
答案 1 :(得分:3)
我还在你的另一个问题中提供了我的答案,但我也在这里写,因为这个答案只与这个问题有关
要在视图出现之前滚动最后一个索引处的视图而不崩溃,首先需要触发collectionView数据的重新加载。重新加载后,请调用您的方法滚动视图。
-(void)viewWillAppear:(BOOL)animated {
[collectionView reloadData];
[self scrollToLastMessageAnimated:YES];
}
[collectionView setContentOffset:CGPointMake(0, CGFLOAT_MAX)]
答案 2 :(得分:3)
Swift 3.0代码:
let index = IndexPath(item: (self.mFetchedResultsControllerVar?.fetchedObjects?.count)! - 1, section: 0)
self.collectionView?.scrollToItem(at: index, at: UICollectionViewScrollPosition.bottom, animated: true)
答案 3 :(得分:0)
处理多个/ 0个部分/项目的更简单的解决方案
[(id , in, available_service_type_ids and available_service_type_ids[0] and available_service_type_ids[0][2] or False)]
答案 4 :(得分:0)
此扩展程序滚动到实际包含项目的最后一部分。 迄今为止的最佳方法。
public extension UICollectionView {
func scrollToLastItem() {
scrollToLastItem(animated: true, atScrollPosition: .bottom)
}
func scrollToLastItem(animated: Bool, atScrollPosition scrollPosition: UICollectionViewScrollPosition) {
guard numberOfSections > 0 else {
return
}
var sectionWithItems: SectionInfo?
for section in Array(0...(numberOfSections - 1)) {
let itemCount = numberOfItems(inSection: section)
if itemCount > 0 {
sectionWithItems = SectionInfo(numberOfItems: itemCount, sectionIndex: section)
}
}
guard let lastSectionWithItems = sectionWithItems else {
return
}
let lastItemIndexPath = IndexPath(row: lastSectionWithItems.numberOfItems - 1, section: lastSectionWithItems.sectionIndex)
scrollToItem(at: lastItemIndexPath, at: scrollPosition, animated: animated)
}
}
答案 5 :(得分:-4)
问题实际上是由有问题的Autolayout限制引起的, 看到我的另一个主题是最终帮助我的解决方案:https://stackoverflow.com/a/24033650/2302437