0

I want to find out if a cell is displaying onscreen in a table view.

I tried out willDisplay method but it's of no use. I even tried

if (tableView.indexPathsForVisibleRows?.contains(indexPath))! {
                    print("showing now")
}


This function works, But it doesn't print anything when the cell is on screen or as I scroll down. Ex: If I have 5 cells, As the app launches and the cell are on the display, nothing is printed. Also, when I scroll from cells 1 to 5, Nothing is displayed. On contrary, If I scroll back from cells 5 to 1, It will display it, which completely defies my purpose.

I hope you understood my query and can help me with an apt solution.

Cheers!

Imad Ali
  • 3,261
  • 1
  • 25
  • 33
Aakash Dave
  • 866
  • 1
  • 15
  • 30

2 Answers2

1

willDisplay method of tabView should work for you.

Give DataSource and Delegate properly. Control+drag from TableView to yellow icon will display you correct options.

enter image description here

Add extension to ViewControllerClass and confirm table protocols-:

extension ViewController : UITableViewDelegate,UITableViewDataSource{

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }// Default is 1 if not implemented

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


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        cell?.textLabel?.text = indexPath.row
        return cell!
    }

    // will display prints while displaying cells

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print("visible now")
    }
Tushar Sharma
  • 2,839
  • 1
  • 16
  • 38
0

Remember to connect UITableView's delegate property and conform to UITableViewDelegate.

Try

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    print("cell \(indexPath.row) is about to display")
}

from UITableViewDelegate's protocol. Documentation could be found here.

krlbsk
  • 1,051
  • 1
  • 13
  • 24