Tom*_*mer 19 uicollectionview swift
我想将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)
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*mer 22
我在查询完成后添加了以下行来运行.
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)
Run Code Online (Sandbox Code Playgroud)
对于 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)
}
Run Code Online (Sandbox Code Playgroud)
针对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)
Run Code Online (Sandbox Code Playgroud)
对于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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15921 次 |
| 最近记录: |