Ios 将UITableViewCell背景设置在XIB之外
在加载表视图时,我无法设置单元格的背景颜色,无论它保持与XIB中声明的颜色相同。此表视图仍将像XIB一样为白色:Ios 将UITableViewCell背景设置在XIB之外,ios,objective-c,cocoa-touch,Ios,Objective C,Cocoa Touch,在加载表视图时,我无法设置单元格的背景颜色,无论它保持与XIB中声明的颜色相同。此表视图仍将像XIB一样为白色: -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReu
-(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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
cell.textLabel.textColor = [UIColor lightGrayColor];
UIColor *cellBackColor = [UIColor orangeColor];
cell.backgroundColor = cellBackColor;
return cell;
}
如何确保方法中的颜色与表视图中的颜色一致
注意:显然,如果我可以在XIB中更改它,但最终我希望颜色交替。
UITableViewCell
有一个内容视图。您可以通过contentView
属性访问它。这就是为什么你看不到细胞的颜色改变。内容视图覆盖单元格的整个框架,并包含添加到单元格中的所有视图。您可以更改其backgroundColor
以查看效果
作为更好的解决方案,您可以为单元格的backgroundView
属性指定一个新视图
cell.backgroundView = [[UIView alloc]initWithFrame:cell.frame];
cell.backgroundView.backgroundColor = [UIColor blueColor];
您也可以使用
backgroundView
将背景设置为自定义图像。尝试将用于更改背景颜色的代码放在表格视图的willDisplayCell:forRowAtIndexPath:delegate方法中:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *cellBackColor = [UIColor orangeColor];
cell.backgroundColor = cellBackColor;
}
在cellForRowAtIndexPath方法中使用:
cell.contentView.backgroundColor=[UIColor redColor] @anupdas我不太熟悉
CGRectZero
。它的作用是什么?这只会改变文本后面的颜色,使文本看起来像是高亮显示的白色,而不是整个单元格改变颜色。当我在IBAction中设置单元格的背景色时,它看起来就大不相同了。编辑:我刚刚将笔尖中的背景色更改为透明,谢谢!