2017-04-10 33 views
0

我試圖追加我的UITableView與更多的行,一旦用戶到達UITableView的底部。但是,一旦我試圖滾動到下調用更多的數據,我得到一個錯誤,指出:如何在分頁時將行添加到UITableView?

fatal error: Index out of range 

這裏是我的代碼:

func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    let contentOffset = scrollView.contentOffset.y 
    let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height; 
    if !isLoadingMore && (maximumOffset - contentOffset <= threshold) { 
     self.isLoadingMore = true 

     DispatchQueue.main.async() { 
      self.fetchMovieData() 
      self.isLoadingMore = false 
     } 
    } 
} 

我也保持跟蹤有多少行被添加到我的添加到我的ROWNUMBER伯爵表視圖更多的數據被稱爲:

var rowNumber: Int = 0 

這裏是我提出我的要求:

func fetchMovieData(_ url: String,_ params: Dictionary<String, String>) { 
     if more { 
      Alamofire.request(url, parameters: params) 
       .responseJSON { 
        response in 
        switch response.result { 
        case .success(let value): 
         self.currentPageNumber += 1 
         let json = JSON(value) 
         self.movieObject = [MovieModel.init(data: json)] 
         self.rowNumber += self.movieObject[0].movieList[0].movieDict.count 
         self.tableView.reloadData() 
        case .failure(let error): 
         print(error) 
       } 
      } 
     } 
    } 

所以我想我的問題是我應該叫:

self.tableView.reloadData() 

爲了追加我的表視圖更多的數據,或者是沒有辦法,我失去了一些東西?

+0

嗯,這應該這樣做。看起來你的問題在於:'self.movi​​eObject = ...' - 你創建新模型,替換舊模型。您應該構建模型對象,以便您可以向其添加新數據。 – Losiowaty

回答

2

問題是你沒有在數組中追加更多的數據,而是用新數據替換舊數據,例如保持數組數爲10,但行數會增加,所以索引超出範圍錯誤將會發生,因爲您嘗試訪問數組[11],但您只有10個元素在該數組中。

爲了解決這個嘗試用它來取代你的函數:

func fetchMovieData(_ url: String,_ params: Dictionary<String, String>) { 
    if more { 
     Alamofire.request(url, parameters: params) 
      .responseJSON { 
       response in 
       switch response.result { 
       case .success(let value): 
        self.currentPageNumber += 1 
        let json = JSON(value) 
        let newArray = [MovieModel.init(data: json)] 
        for i in newArray { 
        self.movieObject.append(i) 
        } 
        self.movieObject = [MovieModel.init(data: json)] 
        self.rowNumber += self.movieObject[0].movieList[0].movieDict.count 
        self.tableView.reloadData() 
       case .failure(let error): 
        print(error) 
      } 
     } 
    } 
} 
+0

沒錯。我必須調整一些邏輯,但這是正確的答案。謝謝! –