ios - 在 UITableView 中自动更新背景

标签 ios objective-c uitableview

我正在制作一个 iOS 应用程序,它基于 UITableView。我设置的背景是,当没有TableViewCell的时候,背景是自定义背景。当有 TableViewCells 时,应用程序将背景更改为颜色。问题是,应用程序必须强制退出并重新启动才能更改背景。无论如何我可以这样做以便自动更新背景吗?这是我的代码:

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

if (sections == 0 || hasRows == NO)
{
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-app.png"]];

}
else
{
 self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundView = nil;
}

我把它放在我的 viewDidLoad 中

最佳答案

self.viewself.tableView 是同一个 View 对象吗?

您将图像设置为 self.tableView 的背景,并将颜色设置为 self.view 的背景。如果表格 View 是self.view的 subview ,一旦你设置了背景图片,它总是会遮住self.view的背景颜色。

强制退出可能有效,因为您重新运行您的逻辑并且从一开始就没有设置图像背景。尝试将 TableView 的背景 View 设置为 nil:

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

    // Set the background view of the table view
    self.tableView.backgroundView = imageView;
}
else
{
    [[self view] setBackgroundColor:[UIColor whiteColor]];   
    self.tableView.backgroundView = nil;
}

关于ios - 在 UITableView 中自动更新背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765356/

相关文章:

ios - 为什么 return 语句不会停止程序?

ios - 如何继承 UIViewControllers?

iOS7 itms-services 方案不起作用?

objective-c - 是否可以在 Cocoa 中确定文件是否是从别名打开的?

ios - DidSelectRow 方法由于 tapGestureRecognizer 而被禁用

ios - 使用静态 UITableViewController 创建两个部分,第一部分具有非静态数量的单元格

ios - UICollectionView 索引

ios - UITabBarController 在 Storyboard的上方添加新的 UIViewController (Swift)

ios - UIWebview(iOS)中的 Docx 支持?

ios - TableView背景渐变毛刺