Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll UICollectionView to bottom

Tags:

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)         } 
like image 817
Tom Coomer Avatar asked Dec 03 '14 16:12

Tom Coomer


1 Answers

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) 

Update to Swift 5

let item = self.collectionView(self.collectionView, numberOfItemsInSection: 0) - 1 let lastItemIndex = IndexPath(item: item, section: 0) self.collectionView.scrollToItem(at: lastItemIndex, at: .top, animated: true) 
like image 143
Tom Coomer Avatar answered Dec 01 '22 00:12

Tom Coomer