使用 swift 在 Xcode 中插入带有 UIButton(或栏按钮)的新部分

insert new section with UIButton (or Bar button) in Xcode using swift

在 Xcode 中(使用 swift)我有一个包含 3 个部分的 table 视图。我希望在用户点击按钮时插入一个新部分,该部分的标题是从文本字段输入的(文本字段不在 tableView 中)

我熟悉 tableView.insertrow(只要传入正确的 indexPath),但我不知道如何使用 tableView.insertSection(这需要一个 indexSet)。

我正在使用二维数组来填充 table 视图。

var twoDArray = [
["apple", "banana", "pear"],
["carrot", "broccoli"],
["chicken", "beef"]
]

目前我的 headers 的标题存储在一个单独的数组中:

var sections = ["Fruits", "Veggies", "Meats"]

当用户使用 tableView.insertSection 点击按钮时,如何插入一个包含 textField.text 输入的新部分(理想情况下,我希望在不重新加载整个 table 的情况下执行此操作查看)

如果您需要添加第 4 个部分并为部分插入设置动画,您可以这样做:

var twoDArray = [
["apple", "banana", "pear"],
["carrot", "broccoli"],
["chicken", "beef"]
]

var sections = ["Fruits", "Veggies", "Meats"]

//After user presses the button
sections.append("Candy")
twoDArray.append(["Chocolate", "Pure Sugar"])

self.tableView.insertSections(IndexSet(integer: sections.count - 1), with: .automatic)

您只需确保在调用 insertSections 之前设置了数据源数组,否则您会崩溃并出现错误,让您知道您的部分插入需要与源插入相匹配。