无法设置Swift中UITableViewCell内部使用的UIView子类的背景颜色



问题:

在声明我的statusColor变量时,tableView中每个单元格的自定义视图背景颜色始终使用初始颜色集,并且cellForRowAt IndexPath中动态设置的颜色始终被忽略。


这是我的UIView子类:

class SlantedView: UIView {
var path: UIBezierPath!
var backgroundColour: UIColor!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func slantedView() {
// Drawing code
// Get Height and Width
let layerHeight = CGFloat(90)
let layerWidth = CGFloat(300)
// Create Path
let bezierPath = UIBezierPath()
//  Points
let pointA = CGPoint(x: 0, y: 0)
let pointB = CGPoint(x: layerWidth, y: 89)
let pointC = CGPoint(x: layerWidth, y: layerHeight)
let pointD = CGPoint(x: 0, y: layerHeight)
// Draw the path
bezierPath.move(to: pointA)
bezierPath.addLine(to: pointB)
bezierPath.addLine(to: pointC)
bezierPath.addLine(to: pointD)
bezierPath.close()
// Mask to Path
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
layer.mask = shapeLayer
}

override func draw(_ rect: CGRect) {
self.slantedView()
self.backgroundColor = backgroundColour
self.backgroundColor?.setFill()
UIGraphicsGetCurrentContext()!.fill(rect)
}
}



这是我的自定义单元格:

class CustomTableViewCell: UITableViewCell {
var statusColour: UIColor = {
let colour = UIColor.red
return colour
}()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let statusContainer = SlantedView()
statusContainer.backgroundColour = self.statusColour
self.addSubview(statusContainer)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}



这是我的cellForRow方法:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomTableViewCell
cell.statusColour = sampleData[indexPath.row].statusColour //Contains different colours
return cell
}

问题肯定来自UIView子类。根据先前的一些研究,看起来overridden draw function可能导致了这个问题。

我遵循了其他一些Stack Overflow问题中给出的建议,添加了以下几行:

self.backgroundColor?.setFill()
UIGraphicsGetCurrentContext()!.fill(rect)

我可能做错了什么?

提前谢谢。

在wakeFromNib((方法中添加slantedView,而不是init((,并使用属性观测器更改slantedView的背景颜色,如下所示:

class CustomTableViewCell: UITableViewCell {
var statusContainer: SlantedView!
var statusColour: UIColor? {
didSet {
guard let color = statusColour else {
statusContainer.backgroundColor = UIColor.black
return
}
statusContainer.backgroundColor = color
}
}
override func awakeFromNib() {
super.awakeFromNib()
statusContainer = SlantedView(frame: self.bounds)
self.addSubview(statusContainer)
}
}

最后,从绘图中删除最后两条线(_ rect:CGRect(方法:-

override func draw(_ rect: CGRect) {
self.slantedView()
self.backgroundColor = backgroundColour
}

最新更新