Scroll UICollectionView to bottom

前端 未结 13 1167
梦毁少年i
梦毁少年i 2021-02-02 12:05

I would like to scroll the UICollectionView to the bottom so the last item is in the view. I have tried to use scrollToItemAtIndexPath but it does not seem to be working. I want

13条回答
  •  情书的邮戳
    2021-02-02 12:44

    Here's my take in Swift5:

    extension UICollectionView {
    
        public func scrollToLastItem(at scrollPosition: UICollectionView.ScrollPosition, adjustment: CGFloat = 0.0, withAdjustmentDuration duration: TimeInterval = 0.5) {
            let lastSection = self.numberOfSections - 1
            let lastRowInLastSection = self.numberOfItems(inSection: lastSection)
            if lastSection > 0, lastRowInLastSection > 0 {
                let indexPath = IndexPath(row: lastRowInLastSection - 1, section: lastSection)
                let visibleIndexPaths = self.indexPathsForVisibleItems
                if !visibleIndexPaths.contains(indexPath) {
                    self.self.scrollToItem(at: indexPath, at: scrollPosition, animated: true)
                    UIView.animate(withDuration: duration) {
                        switch scrollPosition {
                        case .top, .bottom, .centeredVertically:
                            self.contentOffset.y += adjustment
                        case .left, .right, .centeredHorizontally:
                            self.contentOffset.x += adjustment
                        default:
                            print("Inavlid scrollPosition: \(scrollPosition)")
                        }
                    }
                }
            }
        }
    }
    

提交回复
热议问题