我做了一个简单的项目,我将UITableViewCell
子类化为测试drawrect:
方法。在cellForRowAtIndexPath
中,我设置了每个其他单元格backgroundColor
的背景。它适用于模拟器,但不适用于设备。
我知道有更简单的方法可以获得交替的单元格背景,但这只是一个简单的例子,表明在这种情况下drawRect似乎不适用于我的设备。
这是我的代码:
// The subclassed custom cell
class CustomCell: UITableViewCell {
var fColor: UIColor?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
fColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fColor = UIColor.clearColor()
}
/*
func setFcolor(c:UIColor){
fColor = c
setNeedsDisplay()
}
*/
override func drawRect(rect: CGRect) {
var context: CGContextRef = UIGraphicsGetCurrentContext()
var color: UIColor = fColor!
color.set()
CGContextFillRect(context, rect)
}
}
// My cell creation
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as CustomCell
cell.fColor = indexPath.row % 2 == 0 ? UIColor.whiteColor() : UIColor.blackColor()
cell.textLabel.text="row#\(indexPath.row)"
return cell
}
以下是故事板中的设置:
以下是模拟器上的预期结果:
但在我的设备(iOS7.1)上,每个单元格背景都是白色的
答案 0 :(得分:0)
您需要使用UITableViewCell的backgroundColor属性:
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.whiteColor()
}
else {
cell.backgroundColor = UIColor.blackColor()
}