Я пытаюсь разрешить пользователю вставлять строки в конце разделов, но я получаю сообщение об ошибке. Однако все кажется правильным, поэтому должно быть что-то, чего я не вижу. Может кто-то указать мне в правильном направлении. Прикреплен мой код, ошибка и скриншот таблицы.Вставить строку в конце раздела Ошибка
//
// Test.swift
// Table Views
//
// Created by Deion Long on 7/18/15.
// Copyright (c) 2015 Deion Long. All rights reserved.
//
import UIKit
var array = ["Section 1", "Section 2"]
extension UITableView {
func indexPathForView (view : UIView) -> NSIndexPath? {
let location = view.convertPoint(CGPointZero, toView:self)
return indexPathForRowAtPoint(location)
}
}
class Test: UIViewController, UITableViewDelegate, UITableViewDataSource {
var things:NSMutableArray = ["hi", "bye", "kie"]
@IBAction func editBtnClicked(sender: AnyObject) {
//When not in editing mode already set editing to true
if(table.editing == false){
self.editing = true
println("hi")
table.setEditing(true, animated: true)
}else{
self.editing = false
table.setEditing(false, animated: true)
}
}
@IBOutlet weak var table: UITableView!
@IBAction func doneButton(sender: AnyObject) {
table.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
table.allowsSelectionDuringEditing = true
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return array.count // This was put in mainly for my own unit testing
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return array[section]
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var addRow = self.editing ? 1 : 0
println(addRow)
return addRow + things.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("textInputCell3") as! DetailCell
if (indexPath.row >= things.count && self.editing) {
cell.configure(text: "Add Row", placeholder: "Enter")
} else{
cell.configure(text: things.objectAtIndex(indexPath.row) as! String, placeholder: "Enter")
}
return cell
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.table.setEditing(editing, animated: animated)
if(editing){
table.beginUpdates()
for var i = 0; i < self.table.numberOfSections(); i++
{
var lastRow = table.numberOfRowsInSection(i)
var lastIndex = NSIndexPath(forRow: lastRow, inSection: i)
table.insertRowsAtIndexPaths([lastIndex], withRowAnimation: UITableViewRowAnimation.Automatic)
}
table.endUpdates()
}
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if(indexPath.row >= things.count){
return UITableViewCellEditingStyle.Insert
}else{
return UITableViewCellEditingStyle.Delete
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
things.removeObject(indexPath.row)
table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
else if (editingStyle == UITableViewCellEditingStyle.Insert) {
things.insertObject("123", atIndex: self.things.count)
table.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}
ОШИБКА: Нагрузочное приложение из-за неперехваченное исключение «NSInternalInconsistencyException», причина: «Недопустимое обновление: неверное число строк в разделе 1. Число строк, содержащихся в существующей секции после обновления (5) должно быть равное количеству строк, содержащихся в этом разделе перед обновлением (4), плюс или минус количество строк, вставленных или удаленных из этого раздела (0 вставлено, 0 удалено) и плюс или минус количество строк, перемещенных в или из этот раздел (0 перемещен, 0 удален).
Почему вы используете несколько разделов? У вас есть несколько разделов, но в каждом разделе показаны одни и те же данные. – rmaddy
Когда появляется ошибка? – rmaddy
Ну, в конце концов, разделы будут иметь независимые данные, но я хотел сначала отвести это квадрат. Ошибка возникает, когда я нажимаю зеленый плюс butoon, чтобы добавить строку. – HummingBird24