iPhone UITableView image background when table is

2019-03-14 05:22发布

I would like to show an image background when my UITableView is empty. Currently I tried adding a UIImageView to my view controller that contains a table, but XCode doesn't allow it.

Is there a good way of doing it?

3条回答
爷、活的狠高调
2楼-- · 2019-03-14 05:53

UITableView has a backgroundView property. Set this property to the UIImageView containing your background image.

查看更多
▲ chillily
3楼-- · 2019-03-14 06:06

You could either add an image view on top of the table view or change the background view of the table view.

// Check if table view has any cells
int sections = [self.tableView numberOfSections];
BOOL hasRows = NO;
for (int i = 0; i < sections; i++) {
    BOOL sectionHasRows = ([self.tableView numberOfRowsInSection:i] > 0) ? YES : NO;
    if (sectionHasRows) {
        hasRows = YES;
        break;
    }
}

if (sections == 0 || hasRows == NO)
{
    UIImage *image = [UIImage imageNamed:@"test.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    // Add image view on top of table view
    [self.tableView addSubview:imageView];

    // Set the background view of the table view
    self.tableView.backgroundView = imageView;
}
查看更多
男人必须洒脱
4楼-- · 2019-03-14 06:07

In you numberOfRowsInSection method:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if data.count > 0 {

        return data.count
    }
    else{

        let image = UIImage(named: "Nature")
        let noDataImage = UIImageView(image: image)
        noDataImage.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: tableView.frame.height)
        tableView.backgroundView = noDataImage
        tableView.separatorStyle = .none

        return 0
    }
}

numberOfSections should be greater than 0

查看更多
登录 后发表回答