我认为问题是由于部分具有相同的 dataSource 数组,在您的情况下为 postsArray ,当您在单击按钮时将项目附加到 postsArray 时,相同的 postsArray 是用于其他部分,因此在您将行插入 section 0 后,section 1 抱怨我在插入操作之前和之后的行数不一样,但 section 0 不会抱怨,因为它具有相同的行数和数量postsArray 中的项目数
现在这个问题可以通过两种方式解决:
第一种方法是你也可以为其他部分插入行,然后所有部分的行数与postsArray中的元素数相同
第二种方法是所有部分都有不同的数据源数组,例如第 1 部分的 postsArray1,第 2 部分的 postsArray2 和其他部分相同。现在在这种情况下,您不需要为其他部分插入行,因为每个部分都有不同的 dataSource 数组,更改一个不会影响其他部分。
我做了一个简单的项目来证明上述理论:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(buttonTapped(_:)))
self.navigationItem.rightBarButtonItem = addButton
}
var valuesFirstSection = ["value1", "value2", "value3"]
var valuesSecondSection = ["value1Second", "value2Second", "value3Second"]
//if you want to have the same dataSource array then use this
//var sharedValues = ["value1Shared", "value2Shared", "value3Shared"] // shared dataSource array
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return valuesFirstSection.count
}else {
return valuesSecondSection.count
}
// //if you want to have the same dataSource array then
//use this
//return sharedValues.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if indexPath.section == 0 {
cell.textLabel?.text = valuesFirstSection[indexPath.row]
}else {
cell.textLabel?.text = valuesSecondSection[indexPath.row]
}
return cell
//if you want to have the same dataSource array then
//use this
//cell.textLabel?.text = sharedValues[indexPath.row]
//return cell
}
func buttonTapped(_ sender: UIBarButtonItem) {
//if you want to have the same dataSource array then
//you need to insert the rows for other sections as well
// sharedValues.insert("NewValue0", at: 0)
// self.tableView.insertRows(
// at: [IndexPath(row: 0, section: 0),
// IndexPath(row: 0, section: 1)
// ],
// with: .automatic)
valuesFirstSection.insert("NewValue0", at: 0)
self.tableView.insertRows(
at: [IndexPath(row: 0, section: 0)
],
with: .automatic)
}
}
希望这会有所帮助。