Display image when UITableView is empty

1.3k views Asked by At

I'm trying to display an image when my UITableView is empty, but for some reason the code won't run when the tableView is empty, though it's fine when there are cells:

// Configures cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject!) -> (PFTableViewCell!) {
    let cell = tableView.dequeueReusableCellWithIdentifier("upcomingCell", forIndexPath: indexPath) as! UpcomingTVCell
    cell.configureCell(object)

    //makes it so the separators won't dissapear on us
    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine

    if (self.objects?.count == nil) {
        println("test")
        UIGraphicsBeginImageContext(self.view.frame.size);
        UIImage(named: "homeZero")?.drawInRect(self.view.bounds)
        var backImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        self.tableView.backgroundColor = UIColor(patternImage: backImage)

        } else {
        self.tableView.backgroundColor = UIColor.whiteColor()
        println("this other code ran")

    }

    return cell
}

I've tried self.objects?.count == 0, I've tried using numberOfRowsInSection, and I've tried visibleCells.

What am I missing?

3

There are 3 answers

4
Eric Qian On BEST ANSWER

If there is no objects in the datasource, the function above will not be called. Hence you need to find another place to do it. If your datasource is static (no delete or add operations), I suggest to check if the datasource is empty in viewDidLoad. If the datasource could be changed, then I suggest to do it in the function where you delete the object from datasource. Every time you delete an object, you check the datasource, if it becomes empty then show the image.

2
rmp On

In your numberOfRowsInSection delegate check self.objects?.count if it is equal to 0 (no data) then return 1 else return the count as the number of rows in your table. This will allow the cellForRowAtIndexPath delegate to fire, even where there is not data so you can show your image.

0
Wonjung Kim On

I subclass UITableView with slight modification. If a section contains no cells, then the table shows placeholder view.

class PlaceholderTableView: UITableView {
    @IBOutlet var placeholder: UIView?
    @IBInspectable var emptiableSection:Int = 0


    override func reloadData() {
        super.reloadData()
        let count = self.numberOfRowsInSection(emptiableSection)
        self.placeholder?.hidden =  (count != 0)
    }


}