【问题标题】:Giving certain cells different background colors and borders?给某些单元格不同的背景颜色和边框?
【发布时间】:2016-07-31 20:16:58
【问题描述】:

如何为某些单元格赋予不同的背景颜色和边框?

我尝试搜索它,但唯一的解决方案是给随机单元格指定颜色。

【问题讨论】:

  • 您在寻找什么类型的图案来设置背景颜色?请尝试说明您的问题!
  • 假设我有一个数据列表,例如联系人,一个联系人是我最好的朋友。每个联系人都进入一个单元格,我希望属于最好朋友联系人的单元格是红色的。

标签: ios swift uitableview


【解决方案1】:

这完全取决于您如何确定哪些单元格应该接收它。

例如,如果您希望每个其他单元格都具有带白色边框的红色背景,您可以在 cellForItemAtIndexPath 中执行此操作:

// This changes the cell to w/e you want it to look like
if indexPath.row % 2 == 0 {
    cell.backgroundcolor = UIColor.redColor()
    cell.layer.cornerRadius = 5.0
    cell.layer.masksToBounds = true
    cell.layer.borderColor = UIColor.whiteColor.CGColor()
    cell.layer.borderWidth = 2.0
}
//Because I don't reset the state of the cell in this branch of the if statement, 
//before I update it, this cell could have the white border color, or it could have 
//the green border that is the default. This is all due to the view reusing cells.
// also don't forget to reset the corner radius / masks to bounds, forgetting to do 
//this, will lead to some cells having a corner radius and some not.
else if indexPath.row % 3 == 0 {
    cell.backGroundColor = UIColor.blueColor()
    cell.layer.cornerRadius = 0.0
    cell.layer.masksToBounds = false
}
//this resets the cell to its original state
else {
    cell.backGroundColor = UIColor.whiteColor()
    cell.layer.cornerRadius = 0.0
    cell.layer.masksToBounds = false
    cell.layer.borderColor = UIColor.greenColor.CGColor()
    cell.layer.borderWidth = 2.0
}

但实际上,if 语句中的检查可以是任何东西,只需确保在重用单元格时将单元格的状态重置为其原始状态,然后再重新修改它。

【讨论】:

  • 此代码不起作用,因为随着表格的滚动,您最终会看到很多行颜色错误。
  • 是的。细胞被重复使用。一个单元格可能首先被用作偶数行,因此您的代码会将其变为红色。随着表格的滚动,单元格可能会被重复用于奇数行,但您的代码不会重置颜色,因此它会错误地保持红色。你需要一个else 到你的if 来重置颜色和边框。
  • @rmaddy 这就是为什么我在代码行下方写道,您必须将单元格的状态重置为其原始状态。请先阅读整篇文章。
  • 好的,我错过了你答案的最后一句话。但正如所写的那样,它具有误导性,因为所写的代码会导致问题。如果您发布的代码有一个else 并至少有一条评论说明“重置此处的所有内容”,那么您的答案会更好。鉴于问题的性质,OP 将不知道需要代码来处理这个问题,并最终会发布另一个问题,询问为什么在表格滚动时单元格颜色都是消息。
  • 如果我有 a,b,c,d,e,f,g,h 并且我确定 c 有红色背景怎么办!
【解决方案2】:

根据indexPath属性在cellForRowAtIndexPath中设置单元格的backgroundColorlayer.borderColor/layer.borderWidth...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 2020-05-26
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多