0
votes

I want my swift code to add a new tableview cell every time a button is pressed. You can see in the gif below exactly what I am looking for. This code should add the button in the func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {. Every time the tableview cell button is pressed a new cell with a button in it should appear.

enter image description here

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    private let myArray: NSArray = ["First"]
     var myTableView =  UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
        myTableView.dataSource = self
        myTableView.delegate = self
        
        
        
        self.view.addSubview(myTableView)
        myTableView.translatesAutoresizingMaskIntoConstraints = false
       
myTableView.register(MyCell.self, forCellReuseIdentifier: "MyCell")
   

               
               NSLayoutConstraint.activate([

                   myTableView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.90),
                   myTableView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
                   myTableView.topAnchor.constraint(equalTo: view.topAnchor),
                   myTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),



               ])
        
    }
    
   

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Num: \(indexPath.row)")
        print("Value: \(myArray[indexPath.row])")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
       
        cell.buttonTapCallback = {
           
        }
        return cell
    }
    
}
class MyCell: UITableViewCell {
    
    var buttonTapCallback: () -> ()  = { }
    
    let button: UIButton = {
        let btn = UIButton()
        btn.setTitle("Button", for: .normal)
        btn.backgroundColor = .systemPink
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        return btn
    }()
    
    let label: UILabel = {
       let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 16)
        lbl.textColor = .systemPink
       return lbl
    }()
    
    @objc func didTapButton() {
        buttonTapCallback()
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //Add button
        contentView.addSubview(button)
        button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
        
        //Set constraints as per your requirements
        button.translatesAutoresizingMaskIntoConstraints = false
        button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20).isActive = true
        button.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true
        button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true
        
     
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
2

2 Answers

0
votes

In tableView(_: cellForRowAt:), you need to create the cell using MyCell's init(style:reuseIdentifier:) instead of dequeueReusableCell(withIdentifier:for:), i.e.

let cell = MyCell(style: .default, reuseIdentifier: "MyCell")

Next, in buttonTapCallback closure you need to add a new element to myArray and call reloadData() on myTableView, i.e.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = MyCell(style: .default, reuseIdentifier: "MyCell")
    cell.buttonTapCallback = {[weak self] in
        self?.myArray.append("NewCell-\(indexPath.row)")
        self?.myTableView.reloadData()
    }
    return cell
}

Note: Use Swift types when working with Swift instead of the Objective-C types. Use [String] instead of NSArray in your code.

0
votes

You probably missed actually adding a new item to display

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
       
    cell.buttonTapCallback = { [weak self] in
        guard let self = self else { return }

        self.myArray.append("NewItem")
        self.myTableView.reloadData()
    }
    return cell
}