我正在制作一个 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.view
和self.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/