Подтвердить что ты не робот

Прокрутите 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)    
    }
4b9b3361

Ответ 1

Я добавил строки ниже для запуска после завершения запроса.

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)

Ответ 2

Обновлено для 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)

Ответ 3

Для 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)
    }

Ответ 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)

}

Ответ 5

Swift 4

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

Ответ 6

    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 - моя коллекцияView

Ответ 7

Обновление для 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)
}

Ответ 8

Свифт 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)

Ответ 9

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)

Ответ 10

Вы можете отслеживать верх и низ вашего видимого вида и загружать следующую страницу элементов

  func scrollViewDidScroll(_ scrollView: UIScrollView) {

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

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

Ответ 11

Swift 5 и 4 Просто вызовите эту функцию, если вы хотите отобразить последнюю ячейку в представлении коллекции

//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