- Reload
★ アニメーションなしでリロード
tableView.reloaData()
★ アニメーションありでリロード
// Rowを指定してリロ=ドする
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
dataArray[indexPath.row] = "Item"
tableView.reloadRows(at: [indexPath], with: .automatic)
}
// 複数行のRowを指定してリロ=ドする
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let indexPaths: [IndexPath] = (1...3).map{
IndexPath(row: $0, section: 0)
}
dataArray[1] = "Item1"
dataArray[2] = "Item2"
dataArray[3] = "Item3"
tableView.reloadRows(at: indexPaths, with: .automatic)
}
// Sectionを指定してリロ=ドする
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
dataArray[1] = "Item1"
dataArray[2] = "Item2"
dataArray[3] = "Item3"
tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
}
- Delete
// Rowを1行削除する
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
dataArray.remove(at: indexPath.row)
let index = IndexPath(row: indexPath.row, section: 0)
tableView.deleteRows(at: [index], with: .automatic)
}
// Rowを複数行削除する
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let indexPaths: [IndexPath] = ((indexPath.row)...(indexPath.row + 2)).map{
IndexPath(row: $0, section: 0)
}
dataArray.remove(at: indexPath.row)
dataArray.remove(at: indexPath.row)
dataArray.remove(at: indexPath.row)
tableView.deleteRows(at: indexPaths, with: .automatic)
}
- Insert
// Rowを1行挿入する
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
dataArray.insert("Item", at: indexPath.row + 1)
let index = IndexPath(row: indexPath.row + 1, section: 0)
tableView.insertRows(at: [index], with: .automatic)
}
// Rowを複数行挿入する
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let indexPaths: [IndexPath] = ((indexPath.row + 1)...(indexPath.row + 3)).map{
IndexPath(row: $0, section: 0)
}
dataArray.insert("Item1", at: indexPath.row + 1)
dataArray.insert("Item2", at: indexPath.row + 2)
dataArray.insert("Item3", at: indexPath.row + 3)
tableView.insertRows(at: indexPaths, with: .automatic)
}
★ Section
// 複数行Sectionの挿入、削除
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
isOpen = !isOpen
if isOpen {
// 複数行Section挿入
let indexSet = IndexSet(2...3)
tableView.insertSections(indexSet, with: .fade)
} else {
// 複数行Section削除
let indexSet = IndexSet(2...3)
tableView.deleteSections(indexSet, with: .fade)
}
}