自定义UITableViewCell无法正常工作(drawRect :)在设备上[Swift]

时间:2014-11-01 01:57:24

标签: ios uitableview swift drawrect

我做了一个简单的项目,我将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
}

以下是故事板中的设置:

customcell

customcell2

以下是模拟器上的预期结果:

simulator

但在我的设备(iOS7.1)上,每个单元格背景都是白色的

1 个答案:

答案 0 :(得分:0)

您需要使用UITableViewCell的backgroundColor属性:

if indexPath.row % 2 == 0 {

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

  cell.backgroundColor = UIColor.blackColor()
}