自定义的UITableViewCell不能在设备上运行[drawRect :) [Swift]

问题描述:

我做了一个简单的项目,其中我将UITableViewCell转换为测试drawrect:方法。在cellForRowAtIndexPath我设置了每个其他单元的背景backgroundColor。它适用于模拟器,但不适用于设备。 我知道有更简单的方法来获取交替单元格背景,但这只是一个简单的例子,表明drawRect在这种情况下似乎不适用于我的设备。自定义的UITableViewCell不能在设备上运行[drawRect :) [Swift]

这里是我的代码:

// 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 
} 

这里是故事板的设置:

customcell

customcell2

这里是在模拟器上的预期结果:

simulator

但我的设备(iOS7.1)上的每一个细胞背景是白色的

您需要使用的UITableViewCell的backgroundColor属性:

if indexPath.row % 2 == 0 { 

    cell.backgroundColor = UIColor.whiteColor() 
} 
else { 

    cell.backgroundColor = UIColor.blackColor() 
} 
+0

谢谢,但这不是我的答案寻找。就像我说的有更简单的方法来实现交替的单元格颜色。这只是使用'drawRect:'的一个例子,它不在设备上显示,而是在模拟器上显示。 – 2014-11-16 21:06:01