Masry
Masry

Reputation: 416

UITableView willDisplay cell is drawing all cells before I scroll down

I'm trying to implement infinite scrolling in UITableView by checking the indexpath at "willDisplay cell", however once the table is loaded with data, the "willDisplay cell" func seems to be drawing all cells before I scroll down although the mobile screen can only fit one or two cells at a time.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(indexPath.row)
}

Output without scrolling down:

0
1
2
3
4
5

When I scroll down the "willDisplay cell" func works properly and it prints the indexpath.row one at a time.

What could be the problem here?

Here's a look at the full code:

override func viewDidLoad() {
        super.viewDidLoad()
        postsTableview.delegate = self
        postsTableview.dataSource = self
        let nibName = UINib(nibName: "postTableViewCell", bundle:nil)
        postsTableview.register(nibName, forCellReuseIdentifier: "postTableViewCell")

        loadPosts()           
    }


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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postTableViewCell", for: indexPath) as! postTableViewCell
        return cell
    }

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        print(indexPath.row)
}

I have tried setting the tableview cell height fixed with large value that exceeds the screen height but I still have the same problem

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 1000.0;
    }

Upvotes: 1

Views: 2291

Answers (2)

Masry
Masry

Reputation: 416

It turned out that I needed to set an estimated row height. I'm coming from Android background and this sounds silly to me but it worked out.

postsTableview.estimatedRowHeight = 400
postsTableview.rowHeight = UITableViewAutomaticDimension

Upvotes: 2

Bright
Bright

Reputation: 5741

On your edited question:

There's nothing wrong with iOS, all table/collection view cells are drawn before they are shown; imagine a table view that shows nothing in the beginning when it's shown, would that be weird?

I don't know what you are trying to achieve after the cells are shown, but I believe that's suitable for another question, good luck!

Upvotes: 0

Related Questions