我认为问题是由于具有相同数据源阵列的部分,你的情况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)
}
}
希望这有助于。
尝试删除'tableView.reloadData()'然后运行程序 – 3stud1ant3
删除,仍然不起作用 –
现在还评论'postsArray.append(“你好”)',现在只需插入一行,是否给予错误呢? – 3stud1ant3