- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我试图从 tableViewCell 内的 tableView 中删除项目。该应用程序几乎是一个待办事项列表类型的应用程序,用户可以在其中添加任务,然后可以将具有相同日期的任务分组在一起。
日期位于其自己的表格 View 中,并且在这些日期的单元格中包含属于其下的相应任务的表格 View 。
但是,每当我删除 tableViewCell 中的 tableView 中的任务时,应用程序就会崩溃。
我已经查找了每当删除一行但没有更改时收到的错误。它们仅适用于普通的 tableView。不是 tableViewCell 中的 tableView。
我尝试添加 tableView.beginUpdates()
和 tableView.endUpdates()
但问题仍然存在。我不确定接下来要做什么,因为我认为这应该可行,而且我真的找不到太多关于删除 tableViewCell 的 tableView 中的行的信息。
代码如下:
ToDoListTableViewController.swift(外部tableView)
class ToDoListTableViewController: UITableViewController {
// MARK: - Properties
var toDos = [ToDo]()
var toDoDateGroup = [String]()
var matchedToDoCount: Int = 0
//var savedToDos = [ToDo]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// If there are saved ToDos, load them
if let savedToDos = loadToDos() {
toDos = savedToDos
}
groupToDosAccordingToDates()
sortToDoGroupDates()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//savedToDos = loadToDos()!
groupToDosAccordingToDates()
sortToDoGroupDates()
reloadTableViewData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return toDoDateGroup.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let dateCellIdentifier = "ToDoTableViewCell"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d/yy"
//dateFormatter.dateFormat = "M/d/yy, h:mm a"
guard let cell = tableView.dequeueReusableCell(withIdentifier: dateCellIdentifier, for: indexPath) as? ToDoTableViewCell else {
fatalError("The dequeued cell is not an instance of ToDoTableViewCell.")
}
// Fetches the appropriate toDo for the data source layout.
let toDoDate = toDoDateGroup[indexPath.row]
cell.toDoDate = dateFormatter.date(from: toDoDate)!
cell.toDoDateWeekDayLabel.text = toDoDate
cell.toDoDateWeekDayLabel.backgroundColor = UIColor.green
for toDo in toDos {
//print(dateFormatter.string(from: toDo.workDate))
//print("cell.ToDoDate Below:")
//print(toDoDate)
if dateFormatter.string(from: toDo.workDate) == toDoDate {
cell.toDos.append(toDo)
}
}
matchedToDoCount = cell.toDos.count
//cell.toDoTableView.reloadData()
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
// MARK: - Actions
@IBAction func unwindToToDoList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ToDoItemTableViewController, let toDo = sourceViewController.toDo {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d/yy"
// Update an existing ToDo
//toDos.append(toDo)
toDoDateGroup[selectedIndexPath.row] = dateFormatter.string(from: toDo.workDate)
tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
else {
// Add a new toDo
toDos.append(toDo)
var newIndexPath: IndexPath
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d/yy"
if (toDoDateGroup.isEmpty) {
newIndexPath = IndexPath(row: toDoDateGroup.count, section: 0)
toDoDateGroup.append(dateFormatter.string(from: toDo.workDate))
tableView.insertRows(at: [newIndexPath], with: .automatic)
} else {
groupToDosAccordingToDates()
}
}
// Save the ToDos
saveToDos()
}
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch(segue.identifier ?? "") {
case "AddToDoItem":
os_log("Adding a new ToDo item.", log: OSLog.default, type: .debug)
case "ShowToDoItemDetails":
guard let toDoItemDetailViewController = segue.destination as? ToDoItemTableViewController else {
fatalError("Unexpected destination: \(segue.destination)")
}
guard let selectedToDoItemCell = sender as? ToDoGroupTableViewCell else {
fatalError("Unexpected sender: \(sender)")
}
guard let indexPath = tableView.indexPath(for: selectedToDoItemCell) else {
fatalError("The selected cell is not being displayed by the table")
}
let selectedToDoItem = toDos[indexPath.row]
toDoItemDetailViewController.toDo = selectedToDoItem
default:
fatalError("Unexpected Segue Identifier; \(segue.identifier)")
}
}
// MARK: - Private Methods
private func saveToDos() {
//sortToDosByWorkDate()
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(toDos, toFile: ToDo.ArchiveURL.path)
if isSuccessfulSave {
os_log("ToDos successfully saved.", log: OSLog.default, type: .debug)
} else {
os_log("Failed to save toDos...", log: OSLog.default, type: .error)
}
}
private func loadToDos() -> [ToDo]? {
return NSKeyedUnarchiver.unarchiveObject(withFile: ToDo.ArchiveURL.path) as? [ToDo]
}
private func groupToDosAccordingToDates() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d/yy"
//dateFormatter.dateFormat = "M/d/yy, h:mm a"
var newIndexPath: IndexPath
for toDo in toDos {
print(toDo.taskName)
let chosenWorkDate = dateFormatter.string(from: toDo.workDate)
if !toDoDateGroup.contains(chosenWorkDate) {
print(chosenWorkDate)
newIndexPath = IndexPath(row: toDoDateGroup.count, section: 0)
toDoDateGroup.append(chosenWorkDate)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
private func sortToDoGroupDates() {
toDoDateGroup = toDoDateGroup.sorted(by: {
$1 > $0
})
}
private func reloadTableViewData() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
ToDoTableViewCell.swift(内部tableView)
class ToDoTableViewCell: UITableViewCell, UITableViewDataSource, UITableViewDelegate {
// MARK: - Properties
@IBOutlet weak var toDoDateWeekDayLabel: UILabel!
@IBOutlet weak var toDoTableView: UITableView!
var toDos = [ToDo]()
let dateFormatter = DateFormatter()
var toDoDate = Date()
let cellIdentifier = "ToDoGroupTableViewCell"
override var intrinsicContentSize: CGSize {
return self.intrinsicContentSize
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
dateFormatter.dateFormat = "M/d/yy, h:mm a"
sortToDosByWorkDate()
//reloadTableViewData()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
toDoTableView.delegate = self
toDoTableView.dataSource = self
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print("Inner Cell Data");
return toDos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "ToDoGroupTableViewCell"
let dueDateFormatter = DateFormatter()
let workDateFormatter = DateFormatter()
dueDateFormatter.dateFormat = "M/d/yy, h:mm a"
workDateFormatter.dateFormat = "h:mm a"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ToDoGroupTableViewCell else {
fatalError("The dequeued cell is not an instance of ToDoGroupTableViewCell.")
}
// Fetches the appropriate toDo for the data source layout.
let toDo = toDos[indexPath.row]
cell.taskNameLabel.text = toDo.taskName
cell.workDateLabel.text = workDateFormatter.string(from: toDo.workDate)
cell.estTimeLabel.text = toDo.estTime
cell.dueDateLabel.text = dueDateFormatter.string(from: toDo.dueDate)
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source of the current tableViewCell
let toDoToBeDeleted = toDos[indexPath.row]
tableView.beginUpdates()
toDos.remove(at: indexPath.row)
saveToDos(toDoToBeDeleted: toDoToBeDeleted)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
} 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
}
}
// MARK: - Private Methods
private func saveToDos(toDoToBeDeleted: ToDo?) {
// TODO: Refactor the deletion part of this function to be its own delete function
// If there are existing toDos, load them
if var savedToDos = loadToDos() {
// If a there is a specific toDo to be deleted after save
if toDoToBeDeleted != nil {
print("toDoToBeDeleted is not nil")
print(savedToDos)
/*while let toDoIdToDelete = savedToDos.index(of: toDoToBeDeleted!) {
print("Index Exists in savedToDos")
savedToDos.remove(at: toDoIdToDelete)
}*/
savedToDos.removeAll{$0 == toDoToBeDeleted}
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(savedToDos, toFile: ToDo.ArchiveURL.path)
if isSuccessfulSave {
os_log("A ToDo was deleted and ToDos is successfully saved.", log: OSLog.default, type: .debug)
}
// If there is no specific toDo to be deleted
} else {
let lastToDosItem: Int = toDos.count - 1
savedToDos.append(toDos[lastToDosItem])
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(savedToDos, toFile: ToDo.ArchiveURL.path)
if isSuccessfulSave {
os_log("A ToDo was added and ToDos is successfully saved.", log: OSLog.default, type: .debug)
}
}
// If this is the initial save and no other toDos exists
} else {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(toDos, toFile: ToDo.ArchiveURL.path)
if isSuccessfulSave {
os_log("The initial ToDo is successfully saved.", log: OSLog.default, type: .debug)
}
}
}
private func loadToDos() -> [ToDo]? {
print("loadToDos()")
return NSKeyedUnarchiver.unarchiveObject(withFile: ToDo.ArchiveURL.path) as? [ToDo]
}
private func registerCell() {
toDoTableView.register(ToDoTableViewCell.self, forCellReuseIdentifier: "ToDoTableViewCell")
}
private func sortToDosByWorkDate() {
toDos = toDos.sorted(by: {
$1.workDate > $0.workDate
})
}
}
在 tableViewCell 中删除 tableView 中的行时出现错误输出:
2019-08-05 00:35:03.610047-0400 Focus-N-Do[1957:40199] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
*** First throw call stack:
(
0 CoreFoundation 0x00000001095501bb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x0000000107b66735 objc_exception_throw + 48
2 CoreFoundation 0x000000010954ff42 +[NSException raise:format:arguments:] + 98
3 Foundation 0x0000000107569877 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 194
4 UIKitCore 0x000000010c0e2e2d -[UITableView _endCellAnimationsWithContext:] + 18990
5 UIKitCore 0x000000010c0fc711 -[UITableView endUpdates] + 75
6 Focus-N-Do 0x00000001071201ac $S10Focus_N_Do02ToB13TableViewCellC05tableE0_6commit8forRowAtySo07UITableE0C_So0leF12EditingStyleV10Foundation9IndexPathVtF + 1036
7 Focus-N-Do 0x000000010712029b $S10Focus_N_Do02ToB13TableViewCellC05tableE0_6commit8forRowAtySo07UITableE0C_So0leF12EditingStyleV10Foundation9IndexPathVtFTo + 123
8 UIKitCore 0x000000010c120d90 __48-[UITableView _animateDeletionOfRowAtIndexPath:]_block_invoke + 71
9 UIKitCore 0x000000010c3b6235 +[UIView(Animation) performWithoutAnimation:] + 90
10 UIKitCore 0x000000010c120bdb -[UITableView _animateDeletionOfRowAtIndexPath:] + 219
11 UIKitCore 0x000000010c129739 __82-[UITableView _contextualActionForDeletingRowAtIndexPath:usingPresentationValues:]_block_invoke + 59
12 UIKitCore 0x000000010c07ef5e -[UIContextualAction executeHandlerWithView:completionHandler:] + 154
13 UIKitCore 0x000000010c084884 -[UISwipeOccurrence _performSwipeAction:inPullview:swipeInfo:] + 725
14 UIKitCore 0x000000010c086128 -[UISwipeOccurrence swipeActionPullView:tappedAction:] + 92
15 UIKitCore 0x000000010c08ad33 -[UISwipeActionPullView _tappedButton:] + 138
16 UIKitCore 0x000000010bedbecb -[UIApplication sendAction:to:from:forEvent:] + 83
17 UIKitCore 0x000000010b9170bd -[UIControl sendAction:to:forEvent:] + 67
18 UIKitCore 0x000000010b9173da -[UIControl _sendActionsForEvents:withEvent:] + 450
19 UIKitCore 0x000000010b91631e -[UIControl touchesEnded:withEvent:] + 583
20 UIKitCore 0x000000010bf170a4 -[UIWindow _sendTouchesForEvent:] + 2729
21 UIKitCore 0x000000010bf187a0 -[UIWindow sendEvent:] + 4080
22 UIKitCore 0x000000010bef6394 -[UIApplication sendEvent:] + 352
23 UIKitCore 0x000000010bfcb5a9 __dispatchPreprocessedEventFromEventQueue + 3054
24 UIKitCore 0x000000010bfce1cb __handleEventQueueInternal + 5948
25 CoreFoundation 0x00000001094b5721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
26 CoreFoundation 0x00000001094b4f93 __CFRunLoopDoSources0 + 243
27 CoreFoundation 0x00000001094af63f __CFRunLoopRun + 1263
28 CoreFoundation 0x00000001094aee11 CFRunLoopRunSpecific + 625
29 GraphicsServices 0x000000011166b1dd GSEventRunModal + 62
30 UIKitCore 0x000000010beda81d UIApplicationMain + 140
31 Focus-N-Do 0x00000001071230b7 main + 71
32 libdyld.dylib 0x000000010a9e9575 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
如有任何帮助,我们将不胜感激。
最佳答案
问题不在于 beginUpdates
、endUpdates
等,而在于 ToDoTableViewCell
逻辑。
正如错误文本提示的那样,您删除和/或插入的行数不正确。
考虑这个例子:您从数据源中删除 1 个对象(即 toDos
),您为一个 indexPath 调用
。 tableView.deleteRows(at: [indexPath], with: .fade)
既然如此,那就万事大吉了。但错误表明更新前有 3 行,现在更新后有 5 行。请记住,您删除了 1 行,因此应该有 2 行。怎么会发生这种情况?...应用程序崩溃。
问题是您正在将对象插入到数据源中的某处,但没有调用tableView.inserRows(...)
。你需要弄清楚这一点。
关于iOS Swift - 删除 tableViewCell 中 tableview 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57352362/
有没有办法在 .swift 文件(编译成 .swift 模块)中声明函数,如下所示: 你好.swift func hello_world() { println("hello world")
我正在尝试使用 xmpp_messenger_ios 和 XMPPFramework 在 iOS 上执行 MUC 这是加入房间的代码。 func createOrJoinRoomOnXMPP()
我想在我的应用程序上创建一个 3D Touch 快捷方式,我已经完成了有关快捷方式本身的所有操作,它显示正确,带有文本和图标。 当我运行这个快捷方式时,我的应用程序崩溃了,因为 AppDelegate
我的代码如下: let assetTag = Expression("asset_tag") let query2 = mdm.select(mdm[assetTag],os, mac, lastRe
我的 swift 代码如下所示 Family.arrayTuple:[(String,String)]? = [] Family.arrayTupleStorage:String? Family.ar
这是我的 JSON,当我读取 ord 和 uniq 数据时出现错误 let response2 : [String: Any] = ["Response":["status":"SUCCESS","
我想将 swift 扩展文件移动到 swift 包中。但是,将文件移动到 swift 包后,我遇到了这种错误: "Type 'NSAttributedString' has no member 'ma
使用CocoaPods,我们可以设置以下配置: pod 'SourceModel', :configurations => ['Debug'] 有什么方法可以用 Swift Package Manag
我正在 Xcode 中开发一个 swift 项目。我将其称为主要项目。我大部分都在工作。我在日期选择器、日期范围和日期数学方面遇到了麻烦,因此我开始了另一个名为 StarEndDate 的项目,其中只
这是 ObjectiveC 代码: CCSprite *progress = [CCSprite spriteWithImageNamed:@"progress.png"]; mProgressBar
我正在创建一个命令行工具,在 Xcode 中使用 Swift。我想使用一个类似于 grunt 的配置文件确实如此,但我希望它是像 Swift 包管理器的 package.swift 文件那样的快速代码
我假设这意味着使用系统上安装的任何 swift 运行脚本:#!/usr/bin/swift 如何指定脚本适用的解释器版本? 最佳答案 Cato可用于此: #!/usr/bin/env cato 1.2
代码说完全没问题,没有错误,但是当我去运行模拟器的时候,会出现这样的字样: (Swift.LazyMapCollection (_base:[ ] 我正在尝试创建一个显示报价的报价应用。 这是导入
是否可以在运行 Swift(例如 Perfect、Vapor、Kitura 等)的服务器上使用 RealmSwift 并使用它来存储数据? (我正在考虑尝试将其作为另一种解决方案的替代方案,例如 no
我刚开始学习编程,正在尝试完成 Swift 编程书中的实验。 它要求““编写一个函数,通过比较两个 Rank 值的原始值来比较它们。” enum Rank: Int { case Ace = 1 ca
在您将此问题标记为重复之前,我检查了 this question 它对我不起作用。 如何修复这个错误: error: SWIFT_VERSION '5.0' is unsupported, suppo
从 Xcode 9.3 开始,我在我的模型中使用“Swift.ImplicitlyUnwrappedOptional.some”包裹了我的字符串变量 我不知道这是怎么发生的,但它毁了我的应用程序! 我
这个问题在这里已经有了答案: How to include .swift file from other .swift file in an immediate mode? (2 个答案) 关闭 6
我正在使用 Swift Package Manager 创建一个应用程序,我需要知道构建项目的配置,即 Debug 或 Release。我试图避免使用 .xcodeproj 文件。请有人让我知道这是否
有一个带有函数定义的文件bar.swift: func bar() { println("bar") } 以及一个以立即模式运行的脚本foo.swift: #!/usr/bin/xcrun s
我是一名优秀的程序员,十分优秀!