簡體   English   中英

TableView Load More正在不斷獲取

[英]TableView Load More is fetching non-stop

我設置一個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)。

我在另一個SO問題中找到了答案。 這里適用於我的情況

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM