【问题标题】:How to click on a button in a custom table header and have a row added under the section the button was clicked in? [closed]如何单击自定义表格标题中的按钮并在单击按钮的部分下添加一行? [关闭]
【发布时间】:2020-10-11 12:45:35
【问题描述】:

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

【问题讨论】:

  • 欢迎这样做!能否请您发布您到目前为止使用的代码?

标签: ios swift uitableview xcode8 uitableviewsectionheader


【解决方案1】:

考虑以下代码:

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

【讨论】:

  • 谢谢!这没有任何问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2020-07-21
相关资源
最近更新 更多