如何单击自定义 table header 中的按钮并在单击按钮的部分下方添加一行?

How to click on a button in a custom table header and have a row added under the section the button was clicked in?

基本上我有一个带有不同部分的自定义 header 的表格视图。在我用于 headers 的自定义单元格中,我有一个按钮。单击该按钮后,我想在单击该按钮的部分下添加一行。关于如何执行此操作的任何建议?

考虑以下代码:

import UIKit

class ViewController: UITableViewController {

    let cellId = "cellId"
    
    var twoDimensionalArray = [
        ["Amy", "Bill", "Max", "Jack", "Jill", "Mary"],
        ["Amy", "aa", "Steve", "bb", "Jill", "Mary"]
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
    }
    
    @objc func handleAddButtonDidTap(button: UIButton) {
        let section = button.tag

        twoDimensionalArray[section].insert("New Content", at: 0)
        let indexPath = IndexPath(row: 0, section: section)
        
        //take care of reloading your tableView
        tableView.beginUpdates()
        tableView.insertRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
    }
    
    //could be refactored into an own UITableViewFooterHeaderView class
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let button = UIButton(type: .system)
        button.setTitle("Add new cell", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.backgroundColor = .gray
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        
        button.addTarget(self, action: #selector(handleAddButtonDidTap), for: .touchUpInside)
        
        button.tag = section //with the help of button.tag we keep track of which section header was clicked.

        return button
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 36
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return twoDimensionalArray.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return twoDimensionalArray[section].count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let name = twoDimensionalArray[indexPath.section][indexPath.row]
        
        cell.textLabel?.text = name
        return cell
    }
}