2016-10-22 41 views
1

其他行我用斯威夫特3. 我的UITableView 7行:添加在TableView中

override func viewDidLoad() { 
     super.viewDidLoad()   
     self.tableView.delegate = self 
     self.tableView.dataSource = self   
} 

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int 
    {   
     return 7 
    } 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    if (IndexPath.row == 6) 
    { 
     tableView.beginUpdates() 
     var index = IndexPath(row: 7, section: 0) 
     tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)      
     tableView.endUpdates() 
    } 
} 

我要添加額外的電池,當我滾動到最後一個單元格表。 但我得到這個錯誤:

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

回答

1

當您插入或刪除的tableView,SOT的對象的數量保持等於行的數量的tableView

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {   
    return dataSource.count 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    if (IndexPath.row == 6) { 
     tableView.beginUpdates() 
     var index = IndexPath(row: 7, section: 0) 
     let newObject = // create new model object here 
     dataSource.insert(newObject, at: 7) 
     tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)      
     tableView.endUpdates() 
    } 
} 
任何行,您應該更新您的數據源
+0

謝謝!有用 – Kirill