如何更改分组的表格视图单元格的背景?
Posted
技术标签:
【中文标题】如何更改分组的表格视图单元格的背景?【英文标题】:How to change the background of a grouped tableview cell? 【发布时间】:2012-08-13 03:43:30 【问题描述】:我想更改分组表格视图单元格的背景。假设您有 5 个分组单元格。顶部单元格的左上角和右上角是圆角,底部单元格的左下角和右下角是圆角,中间单元格没有圆角。这就是问题所在。如果我设置每个单元格的背景,顶部和底部单元格看起来就像中间的单元格,没有顶部和底部角。如何设置背景以使顶部和底部单元格四舍五入,而不会最终使每个单元格看起来相同。提前致谢。
编辑: 还有另一个旁注。在某些情况下,tableview 单元格只显示一个单元格,这意味着每个角都是圆角的。那么如何设置可以处理所有这些情况的背景。
【问题讨论】:
您要更改背景视图或颜色吗? 不是我想的颜色。因为我正在尝试添加渐变背景。 试试 cell.backgroundView.clipsToBounds = YES; 【参考方案1】:您可以为单元格设置背景渐变,在这种情况下您可能不必担心圆角,因为您使用了 cell.layer。 (对于您项目中的这个导入 Quartz 框架)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if (indexPath.row == 0) // first cell
// set background gradient
CAGradientLayer *gradient = [[CAGradientLayer alloc] init];
gradient.position = CGPointMake(0, 0);
gradient.frame = cell.frame;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.207 green:0.207 blue:0.207 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.125 green:0.125 blue:0.125 alpha:1.0] CGColor], nil];
[[cell.layer.sublayers objectAtIndex:0] removeFromSuperlayer];
[cell.layer insertSublayer:gradient atIndex:0];
[gradient release];
else if (indexPath.row == 1) // second cell
//
// Another gradient
//
return cell;
【讨论】:
【参考方案2】:你试过了吗
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
if (indexPath.row == 0)
NSLog(@"Here my first cell");
cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"myFirstCellPicture.png"]];
else
NSLog(@"myOtherCells");
cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"otherCellPicture.PNG"]];
【讨论】:
以上是关于如何更改分组的表格视图单元格的背景?的主要内容,如果未能解决你的问题,请参考以下文章
分组 UITableView 自定义绘制单元格,而不更改背景颜色?