append tableview cell text label into a empty array

451 Views Asked by At

I want to take all of the index path ints displayed on the tableview cells. Right now there is numbers 1-5 on the cells. That is what should be appended to the array emptyA. I have tried to do a compact on the index path but that does not work. All of my code is featured below no uses of storyboards. The code should append the array in view did load.

   import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    var emptyA = [Int]()
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text =    "\([indexPath.row+1])"
     
        return cell
    }
    
    var theTable = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(theTable)
        theTable.frame = CGRect(x: 100, y: 100, width: 100, height: 300)
        theTable.delegate = self
        theTable.dataSource = self
        theTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        //need this part
        emptyA.append()
        
    }


}
1

There are 1 best solutions below

0
On BEST ANSWER

You can add the indexPath.row in emptyA in tableView(_:cellForRowAt:) method, i.e.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = "\([indexPath.row+1])"
    if !emptyA.contains(indexPath.row+1) {
        emptyA.append(indexPath.row+1)
    }
    return cell
}