Handling an empty UITableView. Print a friendly message

前端 未结 22 1207
青春惊慌失措
青春惊慌失措 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 06:14

    First, the problems with other popular approaches.

    BackgroundView

    Background view doesn't center nicely if you were to use the simple case of setting it to be a UILabel.

    Cells, headers, or footers to display the message

    This interferes with your functional code and introduces weird edge cases. If you want to perfectly center your message, that adds another level of complexity.

    Rolling your own table view controller

    You lose built-in functionality, such as refreshControl, and re-invent the wheel. Stick to UITableViewController for the best maintainable results.

    Adding UITableViewController as a child view controller

    I have a feeling you'll end up with contentInset issues in iOS 7+ - plus why complicate things?

    My solution

    The best solution I've come up with (and, granted, this isn't ideal) is to make a special view that can sit on top of a scroll view and act accordingly. This obviously gets complicated in iOS 7 with contentInset madness, but it's doable.

    Things you have to watch out for:

    • table separators get brought to front at some point during reloadData - you need to guard against that
    • contentInset/contentOffset - observe those keys on your special view
    • keyboard - if you don't want the keyboard to get in the way, that's another calculation
    • autolayout - you can't depend on frame changes to position your view

    Once you have this figured out once in one UIView subclass, you can use it for everything - loading spinners, disabling views, showing error messages, etc.

提交回复
热议问题