ios - 如何更优雅地添加/删除表格 View 中的单元格?

标签 ios swift uitableview model

我认为这可能是一个 X Y 问题,所以我首先提供一些背景信息。

我正在构建一个可以显示“表单”的应用程序。用户可以在表单中填写一些内容并创建一些自定义内容。

我认为最合适的做法是使用表格 View 作为表单。我可以在每个表格单元格中显示需要填写的所有文本框。

这是屏幕截图:

enter image description here

点击“添加新输入”按钮时,将在底部插入一个新单元格。如果您向左滑动其中一个输入,您会看到一个“删除”按钮。您可以使用它来删除输入。

如您所见,此 TableView 需要添加和删除行。

最初,我使用的是一个名为“TableViewModel”的 cocoapod,这使得这变得非常简单。但后来我发现a really severe bug在图书馆里,所以我不想再使用它了。

我尝试使用 TableView 的 deleteRowsAtIndexPathsinsertRowsAtIndexPaths 方法。但如果我这样做:

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)
}

删除一行后会出现异常,说 TableView 与数据源不一致。这意味着我必须有代码来处理这种不一致。这肯定会让我的代码更难阅读。

插入方法也是如此。

此外,我需要跟踪每个部分中有多少行。我的代码变得非常困惑且难以维护。

我还搜索了其他库,但它们都很奇怪,不像“tableViewModel”那么简单。它们似乎都要求我为 TableView 创建一个模型。我不明白在我的情况下该怎么做。我只想显示一堆文本字段!

如何更优雅地插入或删除行?我想我要么需要编写 TableView 的扩展,要么学习为我的 TableView 编写模型。但这两种方法我都做不到。

最佳答案

因为您没有任何数据源。另请参阅逻辑:假设您使用 insertRowsAtIndexPaths 添加新行。现在您有 2 行。但是,您的 numberOfRowsInSection 始终返回 1。因此它会崩溃,删除时反之亦然。 TableView 应该与集合(NSArrayNSDictionaryNSSet等)一起使用。 寻求您的帮助:

Already they have nade a form as yours

obj-c easy to understand how table view with data source work

Adding, Updating, Deleting and Moving records using Swift.

关于ios - 如何更优雅地添加/删除表格 View 中的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37278581/

相关文章:

iphone - 如何将复选框添加到 UITableViewCell?

ios - 如何将应用程序链接到 App Store?

ios - Swift:构建还是不构建

ios - UITableView 在开始/结束更新调用调整高度后自动滚动到顶部

ios - 如何知道发送的数据是什么类型?

ios - 以编程方式在 Twitter 上发布视频

ios - UICollectionViewCell内部的UICollectionView-空区域取消触摸

ios - 是否可以在 iOS 中使用多色字体图标?

ios - 自己添加观察者

ios - iPhone 6 上的 CSS - 为什么 DIV 不对齐?