swiftuitableviewcellindexpath

use button to add new utibableview cell to index path


In my swift code below i want to use the button bin to add another tableview cell to the current tableview. Right now 3 tableview cells are in the code when the code builds and runs. The button should have the 4 cell added and then also print 4 in the cell. It should do this for a infinite amount. So 4 5 6 etc. The code uses no storyboards.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }
    
    var btn = UIButton()
    var tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        setTableVIew()
        
        btn.backgroundColor = .systemTeal
        btn.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(btn)
        NSLayoutConstraint.activate([
            btn.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            btn.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
            btn.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.2),
        
        
        ])
        btn.addTarget(self, action: #selector(pressBtn), for: .touchDown)
    }
    
    func setTableVIew(){

        
        let VCframe = self.view.frame
        let height = VCframe.height * 0.8
        let width = VCframe.width
        
        tableView.frame = CGRect(x: 0, y: 0, width: width, height: height)
       
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    @objc func pressBtn(){
        //add another cell with the next index so the next number would be 4
    }
}

Solution

  • The simple way would be to declare the numberOfRows variable at ViewController's scope and append it's value when button is pressed.

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
        //...
        var numberOfRows = 3
        //...
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { numberOfRows }
        //...
        @objc func pressBtn(){
            numberOfRows += 1
            tableView.reloadData()
        }
    }