问题描述
我当前正在尝试向tableView添加一行,我添加视图的代码如下
@IBAction func done(segue:UIStoryboardSegue) {
let newContact = segue.source as! NewContactViewController
FirstName = newContact.firstName
LastName = newContact.lastName
print("Adding the name: " + FirstName + " " + LastName + " to the nameArry")
nameArry.append(FirstName + " " + LastName)
print("Added " + nameArry[nameArry.count - 1] + " to name array")
let indexPath = IndexPath(row: myContact.count + contacts.count - 1,section: 0) // Set the indexPath to the lowest part of the array
tableView.beginUpdates() // Starts the update
tableView.insertRows(at: [indexPath],with: .automatic) // Insert row at the lowest part of the table
tableView.endUpdates() // Ends the update
newContact.firstName = "" // Clears the variable "firstName"
newContact.lastName = "" // Clears the variable "lastName"
view.endEditing(true) // disables Editing,saw it on youtube.
}
我将myContact.count + contacts.count
用于indexPath,因为那是我在tableView上使用的
// Get Number of items in table
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return (myContact.count + contacts.count)
}
我收到以下错误:
Thread 1: Exception: "attempt to insert row 4 into section 0,but there are only 4 rows in section 0 after the update"
解决方法
为什么要删除一个?
library(dplyr)
df %>%
janitor::adorn_totals() %>%
mutate(across(.fns = as.character)) %>%
#mutate_all in `dplyr` < 1.0.0
#mutate_all(as.character) %>%
tidyr::pivot_longer(cols = starts_with('Col'))
# A tibble: 12 x 4
# Name Date name value
# <chr> <chr> <chr> <chr>
# 1 John 23/04/2020 Col1 27
# 2 John 23/04/2020 Col2 26
# 3 John 23/04/2020 Col3 red
# 4 Marco 23/04/2020 Col1 30
# 5 Marco 23/04/2020 Col2 25
# 6 Marco 23/04/2020 Col3 blue
# 7 Tony 23/04/2020 Col1 56
# 8 Tony 23/04/2020 Col2 45
# 9 Tony 23/04/2020 Col3 green
#10 Total - Col1 113
#11 Total - Col2 96
#12 Total - Col3 -
....写这行而不要像这样减去1 ...
let indexPath = IndexPath(row: myContact.count + contacts.count - 1,section: 0)
因为如果要添加一行并从总数中减去它...那么更新后现有部分中包含的行数等于更新前该部分中包含的行数
,我弄清楚了,我没有得到准确的计数,因为我没有在联系人数组中添加任何内容。
contacts.append(Contacts(MyContact: nameArry[nameArry.count - 1],Me: ""))
let indexPath = IndexPath(row: myContact.count + contacts.count - 1,section: 0)