首页 文章

UITableView删除行 . 斯威夫特2

提问于
浏览
3

我有一个基于数组以编程方式创建的表视图 . 我已经启用了按钮项上的编辑按钮,我希望能够从数组中删除该行的值,从而从表视图中删除该值 .

我有以下代码:

class TableViewController: UITableViewController {


var data = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry",
    "Clementine", "Coconut", "Cranberry", "Fig", "Grape", "Grapefruit",
    "Kiwi fruit", "Lemon", "Lime", "Lychee", "Mandarine", "Mango",
    "Melon", "Nectarine", "Olive", "Orange", "Papaya", "Peach",
    "Pear", "Pineapple", "Raspberry", "Strawberry"]


override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 3
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return data.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath)

    cell.textLabel?.text = data[indexPath.row]
    return cell
}



// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}



// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {


        data.removeAtIndex(indexPath.row)

        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}
}

当我运行它,并单击行上的删除按钮时,我收到以下错误:

malloc:对象0x7ffc69f4d580的错误:释放对象的校验和不正确 - 对象可能在被释放后被修改 . 在malloc_error_break中设置断点以进行调试

任何帮助将不胜感激 :)

2 回答

  • 0

    这是因为你在 numberOfSectionsInTableView 函数中返回3 ...

    尝试返回1:

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    
        return 1 // here
    }
    
  • 3

    您声明了3个部分,但只使用了1个,在删除操作之后,您的tableview令人困惑 .

相关问题