Tom Coomer Tom Coomer - 3 months ago 12
Swift Question

Scroll UICollectionView to bottom

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 this to happen after I have completed a query with Parse.com

Thanks

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)
}

Answer

I have added the lines below to run once the query is complete.

        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)
Comments