我認爲問題是由於具有相同數據源陣列的部分,你的情況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