【问题标题】:How to set background color of tableView如何设置tableView的背景颜色
【发布时间】:2011-02-18 19:29:43
【问题描述】:

我一直尝试设置TableView的backgroundColor都没有成功。 当父视图控制器为UIViewContoller 时,将tableView.backgroundColor 和/或cell.backgroundColor 设置为clearColor 不起作用。

我的 nib 文件结构是

FileOwner
View
UITableView

(注意:我将 TableView 设置为 groupedTable 部分)

第一次尝试,我在代码viewDidLoad中创建了UIView

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 300)] autorelease;
[view setBackgroundColor:UIColor blueColor]; // color it just to see if it is created at the right place
[self.tableView sendSubViewToBack:view];

它有效,但它隐藏了单元格的内容。我可以看到标题的内容,但看不到单元格内容。 (但是当我更改视图的坐标(0,150,160,300)时,我可以看到单元格的内容,但随后它失去了 tableview 的 backgroundColor。

第二次尝试, 我创建了 imageView

View
ImageView
UITableView

并设置了self.tableView.backgroundColor = [UIColor clearColor];,但没有用。

我用谷歌搜索,但没有得到平静的答案。

【问题讨论】:

  • 这个问题有答案吗?

标签: iphone xcode uitableview uiviewcontroller


【解决方案1】:

具有分组样式的 UITableView 使用背景视图。要摆脱背景视图并让背景颜色显示,请尝试以下任一方法:

tableView.backgroundView = nil;
tableView.backgroundView = [[[UIView alloc] init] autorelease];

之后,你应该可以正常设置背景颜色了:

tableView.backgroundColor = [UIColor redColor];

顺便说一句,只有一个视图可以是另一个视图的父视图/父视图,视图控制器不是视图。

【讨论】:

  • 感谢drawonward,它有效。它为我提供了几个小时的工具,并在 Google 上搜索了很多。
【解决方案2】:

这一直对我有用:

UITableView *tableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
tableView.backgroundColor = [UIColor redColor];
[parentView addSubview:tableView];

确保 tableView 不为 nil,不隐藏,具有正确的框架,并且已添加到正确的父视图中。

【讨论】:

    【解决方案3】:

    斯威夫特版

        let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.tableView.bounds.size.height))
        backgroundView.backgroundColor = UIColor.redColor()
        self.tableView.backgroundView = backgroundView
    

    【讨论】:

      【解决方案4】:
      UIView* backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
      [backgroundView setBackgroundColor:[UIColor redColor]];
      [self.tableView setBackgroundView:backgroundView];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-11
        • 1970-01-01
        • 2013-05-06
        • 2016-03-16
        • 2012-09-21
        • 2018-10-19
        • 2011-06-14
        • 1970-01-01
        相关资源
        最近更新 更多