Switch calls multiple cases one after another when checking table view tag

I have a collection view with three different cells. Each of the cells contains a table view. So, there are three table views. I've set tags for each of them (from 1 to 3). Now, on my view controller (I set it as the table view's data source when I dequeue collection view's cells) I call table view's data source method for the number of rows. To distinguish table views I check each one's tag. Here is the code for that:

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

    switch tableView.tag {

    case 1:
        if unitItems1 != nil {
            return unitItems1!.count
        } else {
            return 0
        }
    case 2:
        if unitItems2 != nil {
            return unitItems2!.count
        } else {
            return 4
        }
    case 3:
        if unitItems3 != nil {
            return unitItems3!.count
        } else {
            return 4
        }
    default:
        return 0
    }
}

The problem is, when the first cell of the collection view is shown (with the first table view) it works fine. But when I scroll to the second cell, BOTH case 2 and case 3 get executed. After that, the second table view shows data as expected, but when I scroll to the third one, the method doesn't get called.

I can't figure out why two case statements get called one after another, while everything works fine for the first cell. If you have any ideas why this happens (or maybe, you could suggested a better way of checking table view's), I would appreciate your help.

iosswiftuitableviewswitch-statement

Answers

answered 6 months ago Tigran Iskandaryan #1

Actually, the solution is quite simple. The reason of the problem was that collectionView's data source method was dequeueing all the cells one after another, even when they weren't on the screen. Consequently, tableView's inside of each cell were getting set, too. So, their data source method was getting called, hence the problem.

UICollectionView has a property called isPrefetchingEnabled. According to the documentation it denotes whether cells and data prefetching is enabled. The documentation says:

When true, the collection view requests cells in advance of when they will be displayed, spreading the rendering over multiple layout passes. When false, the cells are requested as they are needed for display, often with multiple cells being requested in the same render loop. Setting this property to false also disables data prefetching. The default value of this property is true.

So, to solve the problem, described in the question, I set it to false as soon as my collectionView gets set.

comments powered by Disqus