Проблема:
Цвет фона пользовательского представления для каждой ячейки в моем tableView
всегда использует исходный цвет, установленный при объявлении моей переменной statusColour , и цвет, установленный динамически в 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
может быть причиной проблемы.
Я следовал совету, данному в некоторых других вопросах переполнения стека, добавив следующие строки:
self.backgroundColor?.setFill()
UIGraphicsGetCurrentContext()!.fill(rect)
Что я мог делать не так?
Заранее спасибо.