我目前有一个Xcode项目,它可以加载数据并将它们放在将要排序并放在表格中的数组中。截至目前,当我在viewDidLoad()部分中转到表时,我有一个函数将收集我需要的所有数据。但是为了阻止应用程序崩溃它加载了30的限制。我当前的问题是,一旦用户滚动30个项目,我想在最初的30(标准滚动)下加载30多个。我能想到的唯一方法是重新加载整个表格,这不是很聪明。
我只想要一个标准的滚动功能,你可以在Instagram,Facebook或任何在桌面视图上加载数据的互联网应用程序中看到这些功能。因此,当用户滚动时,更多数据被添加到底部。下面我复制了我用来收集初始数据的代码:
func findAnimalUsers() {
//STEP 1: Find users
let animalQuery = PFQuery(className: "Animals") //choosing class
animalQuery.whereKey("dog", equalTo: animalType.text!) //getting users with animal type user types
animalQuery.limit = 30 //number of users intitally showing
animalQuery.findObjectsInBackground (block: { (objects, error) -> Void in
if error == nil { //if no error
//clean up
self.animalArray.removeAll(keepingCapacity: false)
//STEP 2: Find related objects depending on query setting
for object in objects! {
self.animalArray.append(object.value(forKey: "user") as! String) //objectId of related users
}
//STEP 3: Find users
let query = PFUser.query()
query?.whereKey("objectId", containedIn: self.animalArray) //finding users
query?.addDescendingOrder("createdAt") //how to order users
query?.findObjectsInBackground(block: { (objects, error) -> Void in
if error == nil {
//clean up
self.usernameArray.removeAll(keepingCapacity: false)
self.profilePhotoArray.removeAll(keepingCapacity: false)
self.objectIDArray.removeAll(keepingCapacity: false)
//find related objects depending on query setting
for object in objects! {
self.usernameArray.append(object.object(forKey: "username") as! String)
self.profilePhotoArray.append(object.object(forKey: "profilePhoto") as! PFFile)
self.objectIDArray.append(object.objectId!)
}
} else {
print(error)
}
})
} else {
print(error)
}
})
}
我还添加了表格如何使用此信息的代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//define cell
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! AnimalsCell
//STEP 1: connect data from server to objects
cell.usernameLabel.text = usernameArray[indexPath.row]
cell.objectID = objectIDArray[indexPath.row]
profilePhotoArray[indexPath.row].getDataInBackground (block: { (data, error) in
if error == nil {
cell.profilePhoto.image = UIImage(data: data!)
} else {
print(error)
}
})
所以当这个视图控制器出现在viewDidLoad()中时,我只有findAnimalUsers()来启动初始加载。 如何在向下滚动时加载更多???
答案 0 :(得分:1)
您可以使用tableView
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell , forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == lastElement {
// handle your logic here to get more items, add it to dataSource and reload tableview
}
}
答案 1 :(得分:1)
您可以使用scrollview的委托方法
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
let scrollHeight = scrollView.frame.size.height
if offsetY >= contentHeight - scrollHeight
{
//your logic
}
}