Handling an empty UITableView. Print a friendly message

前端 未结 22 1143
青春惊慌失措
青春惊慌失措 2020-12-04 05:22

I have a UITableView that in some cases it is legal to be empty. So instead of showing the background image of the app, I would prefer to print a friendly message in the scr

22条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 05:55

    Using the backgroundView is fine, but it does not scroll nicely like in Mail.app.

    I did something similar to what xtravar did.

    I added a view outside the view hierarchy of the tableViewController.

    Then i used the following code in tableView:numberOfRowsInSection::

    if someArray.count == 0 {
        // Show Empty State View
        self.tableView.addSubview(self.emptyStateView)
        self.emptyStateView.center = self.view.center
        self.emptyStateView.center.y -= 60 // rough calculation here
        self.tableView.separatorColor = UIColor.clear
    } else if self.emptyStateView.superview != nil {
        // Empty State View is currently visible, but shouldn't
        self.emptyStateView.removeFromSuperview()
        self.tableView.separatorColor = nil
    }
    
    return someArray.count
    

    Basically I added the emptyStateView as a subview of the tableView object. As the separators would overlap the view, I set their color to clearColor. To get back to the default separator color, you can just set it to nil.

提交回复
热议问题