내가 문제가 버튼을 클릭에 postsArray
에 항목을 추가 할 때 귀하의 경우 postsArray
에, 섹션을 위해 같은 은 dataSource 배열을 가진 때문이라고 생각 postsArray
같은, 다른 부분에 사용됩니다 행 section 0
에, section 1
전과 삽입 작업 후 나를 위해 행의 수를 불평하는 것은 동일하지 않습니다,하지만 section 0
나던은 지금이 문제는 두 가지로 해결 될 수 postsArray
에서 같은 행의 수와 항목 수 있기 때문에 불평 방법 :
첫 번째 방법은 당신이 모든 섹션을 postsArray
두 번째 방법으로 요소의 수와 같은 행의 동일한 번호를 가지고뿐만 아니라 다른 부분에 대한 행을 삽입 할 수있는 것은 당신이 모든 부분에 대해 서로 다른는 dataSource 배열을 가지고있다 섹션 1의 경우 postsArray1
, 섹션 2의 경우 postsArray2
, 섹션 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 ("Hello")'지금 당장 간단히 행을 삽입하십시오. 오류도? – 3stud1ant3