Handling an empty UITableView. Print a friendly message

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

    One way of doing it would be modifying your data source to return 1 when the number of rows is zero, and to produce a special-purpose cell (perhaps with a different cell identifier) in the tableView:cellForRowAtIndexPath: method.

    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        NSInteger actualNumberOfRows = ;
        return (actualNumberOfRows  == 0) ? 1 : actualNumberOfRows;
    }
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        NSInteger actualNumberOfRows = ;
        if (actualNumberOfRows == 0) {
            // Produce a special cell with the "list is now empty" message
        }
        // Produce the correct cell the usual way
        ...
    }
    

    This may get somewhat complicated if you have multiple table view controllers that you need to maintain, because someone will eventually forget to insert a zero check. A better approach is to create a separate implementation of a UITableViewDataSource implementation that always returns a single row with a configurable message (let's call it EmptyTableViewDataSource). When the data that is managed by your table view controller changes, the code that manages the change would check if the data is empty. If it is not empty, set your table view controller with its regular data source; otherwise, set it with an instance of the EmptyTableViewDataSource that has been configured with the appropriate message.

提交回复
热议问题