2017-08-03 129 views
0

我想用這個答案Cant insert rows into UITableView - Swift 3插入行到表視圖它工作正常,但他們顯示的問題,但跳過一些數據。如何在UITableView中插入多行

基本上我的問題是我有2D數組var students : [[Student]]?我想插入一段該段有4行。

在表格視圖中顯示插入行的正確方法是什麼?

我試圖到目前爲止

func numberOfSections(in tableView: UITableView) -> Int { 
     return students?.count ?? 0 
    } 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return students?[section].count ?? 0 
    } 

,並插入:

//scrolling down time calling this method 
    func oldestState(){ 
     self.students?.append(getdata()) //Update students property 
     self.newsFeedTableView.beginUpdates() 
     let indexPaths = (0..<(getdata().count)).map { IndexPath(row: $0, section: (self.students?.count)! - 1) } 
     print(indexPaths) 
     self.newsFeedTableView.insertSections([(self.students?.count)! - 1], with: UITableViewRowAnimation.automatic) 
     self.newsFeedTableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.automatic) 
     self.newsFeedTableView.endUpdates() 
    } 

    func getdata() -> [Student]{ 
     var _students = [Student]() 
     for i in itemNumber..<(itemNumber + 4) { 
      let student = Student() 
      student.name = "\(i)" 
      print("adding student roll number : \(student.name)") 
      _students.append(student) 
     } 
     itemNumber += 4 
     return _students 
    } 

check full code

這裏是放出來。如果你看到的日誌,你會看到跳過8日 - 在實現代碼如下

enter image description here

+0

@vadian你能幫我嗎 –

+0

你爲什麼插入行?你可以在改變數據源後調用reloadData –

+0

@AravindAR基本上我想把元素數量限制爲3。當我添加元素四時,元素一應該消失。但我最多花費7天。不能管理這個。會幫助我,請問我該怎麼做。 –

回答

2

我希望這些問題是因爲getdata()方法被調用兩次,因此itemNumber值加4 11行,兩次

試試這個:

let data = getdata() 
self.students?.append(data) //Update students property 
self.newsFeedTableView.beginUpdates() 
let indexPaths = (0..<(data.count)).map { IndexPath(row: $0, section: (self.students?.count)! - 1) } 
+0

沒有運氣給我!它不再工作了 –