如何单击自定义表格标题中的按钮,并在单击按钮的部分下添加一行?

问题描述

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

解决方法

考虑以下代码:

import UIKit

class ViewController: UITableViewController {

    let cellId = "cellId"
    
    var twoDimensionalArray = [
        ["Amy","Bill","Max","Jack","Jill","Mary"],["Amy","aa","Steve","bb","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
    }
}