将UICollectionView滚动到底部

时间:2014-12-03 16:49:58

标签: swift uicollectionview

我想将UICollectionView滚动到底部,以便最后一项位于视图中。我曾尝试使用scrollToItemAtIndexPath,但它似乎没有工作。我想在使用Parse.com完成查询后发生这种情况

由于

    var query = PFQuery(className:"Chat")
    //        query.whereKey("user", equalTo:currentUser)
    query.whereKey("rideId", equalTo:currentObjectId)
    query.orderByDescending("createdAt")
    query.includeKey("user")

    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {
            // The find succeeded.
            NSLog("Successfully retrieved \(objects.count) scores.")
            // Do something with the found objects
            for object in objects {
                NSLog("%@", object.objectId)

                var testId = object.objectId

                println(testId)

                self.orderedIdArray.append(testId)

                var message = object.objectForKey("message") as String
                self.messageString = message
                self.messageArray.append(self.messageString)
                println(message)

                var nameId = object.objectForKey("user") as PFUser
                var username = nameId.username as String
                self.nameString = username
                self.namesArray.append(self.nameString)

                println("username: \(username)")

                self.collectionView?.reloadData()
            }

        } else {
            // Log details of the failure
            NSLog("Error: %@ %@", error, error.userInfo!)
        }
                    NSLog("Ordered: %@", self.orderedIdArray)    
    }

13 个答案:

答案 0 :(得分:18)

我已经在查询完成后添加了下面的行来运行。

        var item = self.collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
        var lastItemIndex = NSIndexPath(forItem: item, inSection: 0)
        self.collectionView?.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: UICollectionViewScrollPosition.Top, animated: false)

答案 1 :(得分:6)

更新了Swift 3:

let item = self.collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
let lastItemIndex = IndexPath(item: item, section: 0)
collectionView?.scrollToItem(at: lastItemIndex, at: UICollectionViewScrollPosition.top, animated: true)

答案 2 :(得分:4)

Swift -

水平滚动 - .Right

垂直滚动 - .Bottom

override func viewDidLayoutSubviews() {
        let section = 0
        let lastItemIndex = self.dateCollectionView.numberOfItemsInSection(section) - 1
        let indexPath:NSIndexPath = NSIndexPath.init(forItem: lastItemIndex, inSection: section)
        self.dateCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Right, animated: false)
    }

答案 3 :(得分:4)

Swift 3 多个部分

/**

 This method scrolls the *UICollectionView* to the last item in the last section

 */

func scrollToLastItem() {

    let lastSection = collectionView.numberOfSections - 1

    let lastRow = collectionView.numberOfItems(inSection: lastSection)

    let indexPath = IndexPath(row: lastRow - 1, section: lastSection)

    self.collectionView.scrollToItem(at: indexPath, at: .right, animated: true)

}

答案 4 :(得分:3)

Swift 4

collectionView?.scrollToItem(at: IndexPath(item: 3, section: 0), at: UICollectionViewScrollPosition.top, animated: false)

答案 5 :(得分:2)

    lstMessages.reloadData()
    let item = self.collectionView(lstMessages, numberOfItemsInSection: 0) - 1
    let lastItemIndex = NSIndexPath(forItem: item, inSection: 0)
    lstMessages.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: UICollectionViewScrollPosition.Top, animated: false)

其中lstMessages是我的collectionView

答案 6 :(得分:2)

Swift 3的更新

func viewScrollButton() {
    let lastItem = collectionView(self.collectionView!, numberOfRowsInSection: 0) - 1
    let indexPath: NSIndexPath = NSIndexPath.init(item: lastItem, section: 0)
    self.collectionView.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: false)
}

答案 7 :(得分:2)

迅速4:

对于水平滚动-.right

对于垂直滚动-.bottom

let lastItemIndex = self.collectionView.numberOfItems(inSection: 0) - 1
let indexPath:IndexPath = IndexPath(item: lastItemIndex, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .right, animated: false)

答案 8 :(得分:1)

Swift 4.2

let lastSection = self.messagesCollectionView.numberOfSections - 1
let lastRow = self.messagesCollectionView.numberOfItems(inSection: lastSection)
let indexPath = IndexPath(row: lastRow - 1, section: lastSection)
self.messagesCollectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.top, animated: true)

答案 9 :(得分:0)

您可以跟踪可见视图的顶部和底部,并加载项目的下一页

  func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
        print("bottom")
    }

    if (scrollView.contentOffset.y <= 0) {
        print("top")
    }
}

答案 10 :(得分:0)

Swift 5和4,当您要显示collectionview的最后一个单元格时,只需调用此函数即可

//MARK:- Collection view Scroll to End
func funColvScrollToEnd()
{
    let item = self.collectionView(self.colv!, numberOfItemsInSection: 0) - 1
    let lastItemIndex = NSIndexPath(item: item, section: 0)
    self.colv?.scrollToItem(at: lastItemIndex as IndexPath, at: .bottom, animated: false)
}
//MARK:- You can use .right/ .left/ .top/ .bottom  

答案 11 :(得分:0)

这是我对 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)")
                    }
                }
            }
        }
    }
}

答案 12 :(得分:0)

快速5 (如果水平动画)

func scrollToIndex(index:Int) {
 self.collectionView?.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true)
}