How can I modify the appearance of 'empty' cells in plain UITableView?

前端 未结 8 2270
广开言路
广开言路 2020-12-08 21:18

If you have a plain (not grouped) UITableView with a single row, the rest of the screen is filled with blank or empty cells. How do you change the appearance of these blank

8条回答
  •  孤街浪徒
    2020-12-08 21:41

    Based on samvermette's answer, but modified to use a background image directly rather than compositing an image from a UITableViewCell subclass. Sam's answer is good, but it will be less performant than just creating a background image directly.

    Create a UIView subclass -- in this example I called it CustomTiledView -- and add the following code to the class:

    - (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"tableview_empty_cell_image"];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM (context, 1, -1); 
    CGContextDrawTiledImage(context, 
                            CGRectMake(0, 0, rect.size.width, image.size.height), 
                            [image CGImage]); 
    }
    

    Add the following code to your tableviewcontroller:

    - (CGFloat)tableView:(UITableView *)tableView 
               heightForFooterInSection:(NSInteger)section {
        // this can be any size, but it should be 1) multiple of the 
        // background image height so the last empty cell drawn
        // is not cut off, 2) tall enough that footer cells
        // cover the entire tableview height when the tableview
        // is empty, 3) tall enough that pulling up on an empty
        // tableview does not reveal the background.
            return BACKGROUND_IMAGE_HEIGHT * 9; // create 9 empty cells
    }
    
    - (UIView *)tableView:(UITableView *)tableView 
                viewForFooterInSection:(NSInteger)section {
        CustomTiledView *footerView = [[CustomTiledView alloc] init];
        return [footerView autorelease];
    }
    

    Finally, you'll need to set the bottom content inset of your tableview to the negative of the value returned from -tableView:heightForFooterInsection: In this example it would be -1*BACKGROUND_IMAGE_HEIGHT*9. You can set the bottom content inset either from the Size Inspector of Interface Builder or by setting the self.tableView.contentInset property from the tableviewcontroller.

    Cheers!

提交回复
热议问题