Ios 如何以编程方式更改单元格的背景色
因此,我的实际问题更为有力。我很好奇是否可以通过编程方式更改单元格的背景颜色,但这取决于单元格是第一个还是第二个,等等 我甚至不确定这是否可能,但我试图实现的是一种梯度效应,当细胞数量增加时利用它们Ios 如何以编程方式更改单元格的背景色,ios,swift,uitableview,uicolor,Ios,Swift,Uitableview,Uicolor,因此,我的实际问题更为有力。我很好奇是否可以通过编程方式更改单元格的背景颜色,但这取决于单元格是第一个还是第二个,等等 我甚至不确定这是否可能,但我试图实现的是一种梯度效应,当细胞数量增加时利用它们 if (indexPath.row % 2) { cell.contentView.backgroundColor = UIColor.redColor() } else { cell.contentView.backgroundCol
if (indexPath.row % 2)
{
cell.contentView.backgroundColor = UIColor.redColor()
}
else
{
cell.contentView.backgroundColor = UIColor.blueColor()
}
我已经尝试过这样的方法,至少让颜色交替,看看我是否能想出下一步该怎么做,但这失败了。交替似乎不是正确的选择,但它可能是开始编程我希望发生的事情的正确方法。是的,可以根据单元格是第一个还是第二个等,以编程方式更改单元格的背景色。在
cellforrowatinexpath
委托方法中,检查行是否为奇数,然后放置不同的背景色,如果为偶数,则放置不同的颜色。通过使用下面的代码,您将获得行的其他颜色
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentTableCellIdentifier"];
cell.textLabel.text = @"Your text goes here";
if(indexPath.row % 2 == 0)
cell.backgroundColor = [UIColor redColor];
else
cell.backgroundColor = [UIColor greenColor];
return cell;
}
斯威夫特:-
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
// Configure the cell...
let cellId: NSString = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell
cell.textLabel.text = "Your text goes here"
if(indexPath.row % 2 == 0)
{
cell.backgroundColor = UIColor.redColor()
}
else
{
cell.backgroundColor = UIColor.greenColor()
}
return cell
}
tableView
在使用单元格绘制行之前将此消息发送给其代理,从而允许代理在显示单元格对象之前对其进行自定义
Swift 4.2
是的,很简单。你试过了吗?您遇到了什么问题?我尝试在indexPath.row上使用if语句,但我不确定这是否正确。我真是不知所措。我很高兴听到它的简单,但是。更新您的问题与您尝试。这是代码在哪里?提供更多上下文。使用cell.backgroundColor而不是cell.contentView.backgorunfColor。需要在
willDisplayCell:ForRowatineXpath
方法中设置背景色,而不是在CellForRowatineXpath
方法中设置背景色。问题被标记为Swift,而不是Objective-C。用适当的语言发布答案。这种方法也很有效,只是试图让3种颜色像上面提到的那样工作,现在摆弄indexPath。那么交替是否仅限于两种颜色?我可以用3或4吗?你可以按你的意愿做任何颜色。答案只是反映了您的代码。但是根据索引路径做任何需要的事情。您可以根据需要使用@JamesChen@rmaddy那么你能举个例子说明我如何使用三种颜色吗?我已经试了一整天了。一个选项是一个简单的if/else if/else
块检查行值。
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.redColor()
}
else {
cell.backgroundColor = UIColor.blueColor()
}
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.red
//OR
productCell.contentView.backgroundColor = UIColor.red
}
else {
cell.backgroundColor = UIColor.blue
}
return cell
}