简体   繁体   English

如何更优雅地在表格视图中添加/删除单元格?

[英]How can I add/remove cells in a table view more elegantly?

I think this is probably an XY problem, so I'll give some background info first. 我认为这可能是一个XY问题,因此我将首先提供一些背景信息。

I am building an app that can show a "form". 我正在构建一个可以显示“表单”的应用程序。 The user can fill in the form with some stuff and create some custom things. 用户可以在表格中填写一些内容并创建一些自定义内容。

I think the most suitable thing to do is to use a table view for the form. 我认为最合适的方法是为表格使用表格视图。 And I can display all the text boxes that need to be fill in, in each of the table cells. 我可以在每个表格单元格中显示所有需要填写的文本框。

Here's a screenshot: 这是屏幕截图:

在此处输入图片说明

The "Add New Input" button will insert a new cell on the bottom when it is tapped. 轻按“添加新输入”按钮后,它将在底部插入一个新单元格。 And if you swipe one of the inputs to the left, you get a "Delete" button. 并且,如果您向左滑动输入的其中之一,则会出现“删除”按钮。 You can use that to delete the input. 您可以使用它来删除输入。

As you can see, this table view needs to add and delete rows. 如您所见,此表视图需要添加和删除行。

Originally, I was using a cocoapod called "TableViewModel" which makes this super easy. 最初,我使用的是名为“ TableViewModel”的cocoapod,它使超级简单。 But then I found a really severe bug in the library so I don't want to use it anymore. 但是后来我在库中发现了一个非常严重的错误 ,所以我不想再使用它了。

I tried using the table view's deleteRowsAtIndexPaths and insertRowsAtIndexPaths methods. 我尝试使用表视图的deleteRowsAtIndexPathsinsertRowsAtIndexPaths方法。 But if I do it like this: 但是,如果我这样做:

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = "Hello"
    return cell
}

// I use motionEnded here because I don't want to add a button or anything just to test this
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Fade)
}

It will result in an exception saying that the table view is inconsistent with the data source after I deleted one row. 删除一行后,将导致异常,表明表视图与数据源不一致。 This means I have to have code to handle this inconsistency. 这意味着我必须具有处理这种不一致的代码。 This will definitely make my code harder to read. 这肯定会使我的代码更难阅读。

The same thing goes with the insert method. 插入方法也一样。

Also, I need to keep track of how many rows there are in each section. 另外,我需要跟踪每个部分中有多少行。 And my code just becomes really messy and unmaintainable with all that. 而且我的代码变得非常混乱,无法进行所有维护。

I have also searched for other libraries but they are all really weird and not as straightforward as "tableViewModel". 我还搜索了其他库,但它们确实很奇怪,不像“ tableViewModel”那样简单。 They all seem to require me to create a model for the table view. 它们似乎都要求我为表视图创建模型。 I don't understand how to do that in my case. 我不了解该如何处理。 I just want to display a bunch of text fields! 我只想显示一堆文本字段!

How can I insert or delete rows more elegantly? 如何更优雅地插入或删除行? I think I either need to write an extension of the table view or learn to write a model for my table view. 我想我要么需要编写表视图的extension ,要么需要学习为表视图编写模型。 But I am able to do neither of these methods. 但是我不能做这两种方法。

Because you don't have any data source . 因为您没有任何data source Also see logically : suppose you add a new row with insertRowsAtIndexPaths . logically也可以看到:假设您使用insertRowsAtIndexPaths添加了新行。 So now you have 2 rows . 因此,现在您有2 rows However your numberOfRowsInSection always returning 1. so it will crash and vice versa for delete. 但是,您的numberOfRowsInSection始终返回1.,因此它将崩溃,反之亦然。 Table view are supposed to work with a collection ( NSArray , NSDictionary , NSSet etc.). 表视图应该与collectionNSArrayNSDictionaryNSSet等)一起使用。 For your help: 您的帮助:

Already they have nade a form as yours 他们已经像你一样裸体了

obj-c easy to understand how table view with data source work obj-c易于理解,带有数据源的表视图如何工作

Adding, Updating, Deleting and Moving records using Swift. 使用Swift添加,更新,删除和移动记录。

You may use a TableView to create the form but you must design an appropriate dataSource to keep track of these data. 您可以使用TableView创建表单,但是必须设计适当的dataSource来跟踪这些数据。 Now the dataSource method must be modified to 现在,必须将dataSource方法修改为

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return yourDataSourceForSection.count
}

You may edit this dataSource when a delete operation is performed as follows 您可以按如下所示执行删除操作时编辑此dataSource

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        //Delete the row from the data source to ensure consistency
        self.array.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
}

You may use a model class as the dataSource . 您可以将模型类用作dataSource

class NewCustomOperation: NSObject {
   var name: String?
   var rejectFloatingPoints: Bool?
   var inputs: AvailableInputs?
   var results: Results?
}

class AvailableInputs: NSObject {
   var name: [String]?
   var description: [String]?
}

class Results: NSObject {
   var name: [String]?
   var formula: [String]?
}

I found a solution! 我找到了解决方案!

I basically keep an array of an array of cells for the table view to display: 我基本上保留一个单元格数组以供表视图显示:

var cells: [[UITableViewCell]] = [[], [], []] // I have 3 sections, so 3 empty arrays

And then I added these data source methods: 然后,我添加了以下数据源方法:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return cells.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cells[section].count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return cells[indexPath.section][indexPath.row]
}

Now, I can add and remove cells super easily: 现在,我可以轻松地添加和删除单元格:

func addCellToSection(section: Int, index: Int, cell: UITableViewCell) {
    cells[section].insert(cell, atIndex: index)
    tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: section)], withRowAnimation: .Left)
}

func removeCellFromSection(section: Int, index: Int) {
    cells[section].removeAtIndex(index)
    tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: section)], withRowAnimation: .Left)
}

With just two lines, I can add/remove cells with animation! 只需两行,我就可以添加/删除带有动画的单元格!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何从表格视图中删除空单元格 - How i can remove the empty cells from my table view 如何在表视图下添加视图,但它会滚动显示单元格? - How do I add a view underneath a Table View, but it scrolls with the cells? 如果我将UISwitch控件添加到每个表视图单元格中,如何判断它属于哪个单元格? - If I add a UISwitch control to each of my table view cells, how can I tell which cell it belongs to? 如何在表格视图中删除空单元格? iOS Swift - How do I remove empty cells in table view? iOS Swift 如何轻按按钮即可撤消对表格视图单元格的重新排序 - How can I undo the reordering of table view cells on the tap of a button 如何获取 Swift 中表格视图单元格数据的总和? - How can I take the sum of table view cells' data in Swift? 如何自定义显示在不同表格视图单元格中的图像? - How can I customize the image displayed in different table view cells? 如何快速订购两个动态表格视图单元格? - How can I order two dynamic table view cells in swift? 如何在运行时正确修改iOS表视图单元格(添加/删除子视图?) - How to correctly modify iOS table view cells at runtime (add/remove subviews?) 如果在关闭时我不知道该视图是否已完全创建,该如何优雅地关闭视图? - How can I elegantly dismiss view if at the moment of dismissing I don't know that view is fully created?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM