Table View ReloadData function not triggering cellForRowAtIndexPath Swift

1.5k views Asked by At

I have seen similar questions asked here but none are very helpful to me specifically.

I am implementing a search bar in my table view and it looks like all is well and there aren't any errors. I have looked through the code a few times and can't find any mistakes. So I began to debug.

Here is my Search function:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    var filtered:[Room] = filterz(rooms, txt: searchText)

    //println(filtered.count)

    if(filtered.count == 0){
        searchActive = false
    } else {
        searchActive = true
    }

    self.tView.reloadData()
}

I can see that this is working perfectly up as it is printing out the correct count. However I'm unsure about the reloadData function. I figured that it would trigger the cellForRowAtIndexPath function which is here:

func  tableView(tableView:UITableView,cellForRowAtIndexPathindexPath:NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("RoomCell", forIndexPath: indexPath) as! UITableViewCell

    var room:Room = rooms[indexPath.row]

    if(searchActive){
        room = filtered[indexPath.row]
    }

    if let nameLabel = cell.viewWithTag(200) as? UILabel{

        nameLabel.text = room.name
        println(room.name)

    }

    if let sizeLabel = cell.viewWithTag(201) as? UILabel{

        sizeLabel.text = room.size
        println(room.size)

    }

    if let vacLabel = cell.viewWithTag(202) as? UILabel{

        vacLabel.text = room.vacant
        println(room.vacant)

    }

    if let taskIm = cell.viewWithTag(203) as? UIImageView{

        taskIm.image = UIImage(named: room.imagename)
    }

    return cell
} 

As you can see I have put in print statements to debug, and it is printing nothing. Is this because the function is not triggered or because there is a problem with my code?

If so, can anyone locate it? All I know for sure is that up till the reloadData() function call everything is working perfectly.

2

There are 2 answers

0
0yeoj On BEST ANSWER

You are redeclaring your var filtered just update the existing filtered used inside your cellForRowAtIndexPathindexPath

0
willrichman On

The most common reason for reloadData not calling cellForRowAtIndexpath is that you either have not hooked up the datasource correctly, or you are not referencing the correct tableView.

Make sure that somewhere in viewDidLoad you have a line that looks like the following:

self.tView.dataSource = self

See this question for someone with a similar problem.

Also, you can make setting the labels much easier on yourself by subclassing UITableViewCell and creating outlets from your labels to the cell class. This will allow you to remove the whole if let sizeLabel = cell.viewWithTag(201) as? UILabel dance.