gpt4 book ai didi

arrays - EditingStyle - 删除数组中的单元格和项目

转载 作者:行者123 更新时间:2023-11-28 08:57:34 25 4
gpt4 key购买 nike

我创建了一个数组

var subjectsData = [ 主题(名称:“投资”,学期:1),主题(名称:“统计”,学期:1),主题(名称:“Studium Universale”,学期:2)]

和一个tableView

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

let subject = subjects[indexPath.row] as Subject
let Semester = "\(subject.semester)"

cell.nameLabel.text = subject.name

cell.semesterLabel.text = "Semester"

cell.semesterNumberLabel.text = Semester

return cell
}

使用 var subjects: [Subject] = subjectsData

我现在尝试创建一个编辑功能以删除单元格/行,从而也删除数组中的相应项目。

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
subjectsData.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}

对我而言,代码看起来合乎逻辑且功能正常,但在运行应用程序时每当我尝试删除行/单元格时崩溃并且我收到错误:

'NSInternalInconsistencyException', reason: '无效更新:第 0 部分中的行数无效。更新 (3) 后现有部分中包含的行数必须等于该部分中包含的行数更新 (3) 之前的部分,加上或减去从该部分插入或删除的行数(0 插入,1 删除)以及加上或减去移入或移出该部分的行数(0 移入,0 移出)。'

每当我删除行/单元格时,数组中的相应项目也应该被删除,但如果我正确理解错误,数组似乎没有更新/删除项目?

如果有人知道为什么会出现此错误以及如何解决它,我将不胜感激。

最佳答案

好的,所以我将 subjectsData.removeAtIndex(indexPath.row) 更改为此 editingStyle 代码

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
subjects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}

因为我说 var subjects: [Subject] = subjectsData

我不知道为什么这会解决错误,但现在当我尝试删除某些内容时,应用程序不再崩溃。

关于arrays - EditingStyle - 删除数组中的单元格和项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32706108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com