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



基本上,我有一个表视图,其中包含不同部分的自定义标题。在我用于页眉的自定义单元格中,我有一个按钮。当单击该按钮时,我想在单击该按钮的部分下添加一行。有什么建议吗?

考虑以下代码:

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
}
}

最新更新