TableView Load More不间断地获取

时间:2015-12-06 01:33:17

标签: ios swift uitableview

我设置了一个TableView并获取了分页数据。对于第1页,因为它没有任何参数(例如/?page=2)命中路线。现在我试图实现无限滚动类加载更多。我每次从底部到第5行时都试着打电话。

当我从底部击中第5个单元格时,此代码执行的操作是不间断的。我认为这是因为桌子从底部停留在第5个细胞上并且不断地从底部向上添加细胞(但它可能只是视觉错觉)

class TableView1: UITableViewController {

  var currentPage: Int = 1
  var results: [JSON]? = []
  var urlEndpoint: String?
  var isLoading = false

  override func viewDidLoad() {
       loadItems()
  }

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // connections to cell..

    let rowsToLoadFromBottom = 5;
    let rowsLoaded = self.results?.count   // count of fetched items

    if (!isLoading && (indexPath.row >= (rowsLoaded! - rowsToLoadFromBottom))) {
            self.loadItems()
    }

    return cell
   }   

loadItems()功能:

   func loadItems() {
      isLoading = true
      urlEndpoint = "http://appurl.app/feed"

   if currentPage != 1 {
        currentPage = currentPage! + 1
        urlEndpoint = "http://appurl.app/feed?page=\(currentPage)"
        // print(urlEndpoint)
    }

   // Alamofire call.. {
       // Error handling

      // Got results {
             self.currentPage = json["current_page"].integer
             self.currentPage = self.currentPage + 1

             self.results = data
             self.tableView.reloadData()
          }
          self.isLoading = false
      }
   }

更新:我已正确获取。现在,我在控制台上看到了page参数的链接。但是,现在它突然加载所有页面(我有6页,所以有6页)所以它并没有真正停止附加,我实际上可以看到像一个循环。

更新2:

self.currentPage = json["current_page"].int!

if self.currentPage == 1 {
   self.results = data // data is json data fetched
   self.tableView.reloadData()
} else {
   var currentCount = self.results!.count;
   let indxesPath : [NSIndexPath] = [NSIndexPath]()

   for result in data {
      self.results?.append(result)
      currentCount++
   }

   self.tableView.insertRowsAtIndexPaths(indxesPath, withRowAnimation: UITableViewRowAnimation.Bottom)
   }                     
  self.currentPage = self.currentPage + 1
  }
  self.isLoading = false

但它在self.tableView.insertRowsAtIndexPaths(indxesPath, withRowAnimation: UITableViewRowAnimation.Bottom)

行上崩溃了
  

错误:无效更新:第0节中的行数无效。更新后现有部分中包含的行数(40)必须等于更新前该部分中包含的行数(20) ,加上或减去从该部分插入或删除的行数(0插入,0删除)和加或减移入或移出该部分的行数(0移入,0移出)。

1 个答案:

答案 0 :(得分:0)

我在another SO question找到了答案。这里它适用于我的场景

if self.currentPage == 1 {
    self.results = data
    self.tableView.reloadData()
} else {
    var currentCount = self.results!.count;
    var indxesPath : [NSIndexPath] = [NSIndexPath]()

    for result in data {
       indxesPath.append(NSIndexPath(forRow:currentCount,inSection:0));
       self.results?.append(result)
       currentCount++
    }

    self.tableView.insertRowsAtIndexPaths(indxesPath, withRowAnimation: UITableViewRowAnimation.Bottom)
}