【问题标题】:UITableView Deleting Row. Swift 2UITableView 删除行。斯威夫特 2
【发布时间】:2016-03-09 14:13:59
【问题描述】:

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

我有以下代码:

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 的错误:释放的校验和不正确 object - 对象可能在被释放后被修改。设置一个 malloc_error_break 中的断点进行调试

任何帮助将不胜感激:)

【问题讨论】:

  • 您声明了三个部分,但其余代码仅使用一个。尝试为numberOfSectionsInTableView返回 1

标签: ios swift uitableview


【解决方案1】:

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

尝试只返回 1:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1 // here
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-03-24
      • 1970-01-01
      • 2017-02-15
      • 2017-07-22
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多