如何正确配置UITableView的空视图?

时间:2015-06-16 16:53:42

标签: ios objective-c uitableview xcode-storyboard

我需要设置一个填充UITableView内容区域的视图,只要该表视图为空,就会显示该视图,否则会隐藏。该视图包含图像,标签和执行简单操作的按钮。我希望能做到两件事:

1)利用backgroundView的{​​{1}}属性和

2)尽可能地利用UITableView,同时尽可能减少代码量(可能使用容器视图?)。

但是,我不确定最好的方法是什么。洞见表示赞赏,特别是如果您已经自己实施了此解决方案。

2 个答案:

答案 0 :(得分:0)

您可以通过多种方式执行此操作,但最简单的(概念上)似乎只是使用具有两个子视图的容器视图:

  • UITableView,当它不为空时可见。
  • 一个UIView,用于保存您的图片/标签/按钮 UITableView是空的。

只需根据UITableView

的内容更改其可见性

即使您只使用UITableView并将backgroundView设置为UIView,当UITableView为空时,显示的数量几乎相同必须完成工作(你仍然需要创建两个视图)。

答案 1 :(得分:0)

首先,您要在viewDidLoad

中设置背景视图
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height)];
//Make this clear and it will be the same as the tableView background color
[backgroundView setBackgroundColor:[UIColor clearColor]];
//We can add anything to this text of images
[backgroundView addSubview:imageView];
//This is the important part
[self.tableView setBackgroundView:backgroundView];

现在要隐藏或查看背景视图,您需要向- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView添加一些逻辑,例如:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //Or wherever your data is
    if([self.data count]>0) {

        self.tableView.backgroundView.hidden=YES;
        return 1;

    }

    else {

        self.tableView.backgroundView.hidden=NO;


    }


    return 0;
}

如果表格中没有任何部分显示视图,只需检查您有多少部分。如果你有部分然后隐藏它。

编辑,显然您也可以在界面构建器中设置UIView。确保它的尺寸正确。加载if:

UIView *view = [[[NSBundle mainBundle]
        loadNibNamed:@"MyView"
        owner:self options:nil]
         firstObject];

再次需要设置它:[self.tableView setBackgroundView:view];

相关问题