Ваш подход был верным:
Вы также должны добавить новый элемент в свой "список предметов"
items.append(newItem)
let selectedIndexPath = IndexPath(row: items.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [selectedIndexPath], with: .automatic)
tableView.endUpdates()
вот и все:)
РЕДАКТИРОВАТЬ: Пример
небольшой пример, который идеально подходит для меня:
class ViewController: UIViewController {
struct Item {
var field_a: String
var field_b: Bool
var field_c: Int
}
// MARK: - properties
var items = [Item]()
// MARK: - object-properties
let tableView = UITableView()
let addButton = UIButton()
// MARK: - system-methods
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.addSubview(addButton)
addButton.titleLabel?.text = "ADD"
addButton.titleLabel?.textColor = .white
addButton.backgroundColor = .blue
addButton.addTarget(self, action: #selector(handleButton), for: .touchUpInside)
tableView.dataSource = self
addButton.anchor(top: nil, leading: nil, bottom: view.bottomAnchor, trailing: view.trailingAnchor, padding: UIEdgeInsets(top: 0, left: 0, bottom: 24, right: 24), size: CGSize(width: 84, height: 48))
tableView.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor)
prepareItems()
}
// MARK: - preparation-methods
func prepareItems() {
items.append(Item(field_a: "cell1", field_b: false, field_c: 0))
items.append(Item(field_a: "cell2", field_b: false, field_c: 0))
items.append(Item(field_a: "cell3", field_b: false, field_c: 0))
}
// MARK: - helper-methods
func appendNewItem(_ item: Item) {
items.append(item)
let selectedIndexPath = IndexPath(row: items.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [selectedIndexPath], with: .automatic)
tableView.endUpdates()
}
// MARK: - action-methods
@objc func handleButton() {
appendNewItem(Item(field_a: "new Cell", field_b: true, field_c: 0))
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let currItem = items[indexPath.row]
cell.textLabel?.text = currItem.field_a
return cell
}
}
fyi: .anchor () - метод, написанный мной.- устанавливает все ограничения AutoLayout.