【问题标题】:Customize UITableView background color自定义 UITableView 背景颜色
【发布时间】:2011-09-12 15:55:45
【问题描述】:

这个问题很简单,但很烦人。我将 groupe 样式 UITableView 放在视图控制器中,并使控制器成为表视图的委托和数据源。

当我改变表格背景的颜色时,我使用:

UIColor *backColor = [UIColor colorWithRed:(15.0 / 255.0) green:(170.0 / 255.0) blue:(230.0 / 255.0) alpha: 0.75f];

[self.myTable setBackgroundColor:backColor];

在tableView:tableView cellForRowAtIndexPath:indexPath 方法中,我只返回一个简单的单元格:

static NSString *CellIdentifier = @"CellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
 reuseIdentifier:moreCellIdentifier] autorelease];
}

cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;

但奇怪的是每个单元格的圆角颜色都不对,我认为这是因为单元格的子视图之一的框架比单元格大,我试图制作框架的子视图很小但仍然失败。有什么想法吗?谢谢。

【问题讨论】:

  • 我认为这是单元格宽度的问题,我继承了 UITableViewCell 并将新的单元格类设置为宽度仅为 200,但在表格视图中,单元格仍然占据几乎整个屏幕宽度。

标签: iphone uitableview colors background


【解决方案1】:

尝试在您的 tableView:tableView cellForRowAtIndexPath:indexPath 函数中使用以下代码。

   NSString *CellIdentifier = [[NSString  alloc] initWithFormat:@"CellIdentifier_%d_%d",indexPath.section,indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    
    if (cell == nil){
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
     reuseIdentifier:moreCellIdentifier] autorelease];
    }
    [CellIdentifier  release];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    return cell;

【讨论】:

  • 这些代码只是改变了将单元格标识符分配给单元格的方式,与我这里遇到的问题无关。
  • @Jhaliya:是的,但它不起作用。我发现这是单元格宽度的问题,我继承 UITableViewCell 并使新的单元格类宽度仅为 200,但在表格视图中,单元格仍然占据几乎整个屏幕宽度。
  • @joe522 :您可以通过为您的单元格提供背景颜色来调试它,并查看它们占据的区域。
  • @Jhaliya:好主意。每次运行我的应用程序时,我都尝试用颜色填充单元格的子视图之一,我发现这是单元格的内容视图超出了单元格的范围
  • @Jhaliya:有什么想法可以减小内容视图的大小并使其小于单元格的框架?我试过 setBound 和 setFrame,在这里都不起作用。
【解决方案2】:

查看您的代码,我不清楚这一行是什么:

[self.myTable setBackgroundColor:backColor];

指。什么是 myTable?什么是自我?

无论如何,如果您使用UITableViewController 来管理您的表格,您应该像这样更改背景颜色:

UIColor *backColor = [UIColor colorWithRed:(15.0 / 255.0) green:(170.0 / 255.0) blue:(230.0 / 255.0) alpha: 0.75f];
tableViewController.tableView.backgroundColor = backColor;

如果您将UITableViewController 子类化,则执行该代码的最佳位置是viewWillAppear(使用self 而不是tableViewController.tableView.backgroundColor)。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2011-10-07
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多