Невозможно установить цвет фона для подкласса UIView, используемого внутри UITableViewCell в Swift - PullRequest
0 голосов
/ 11 апреля 2020

Проблема:

Цвет фона пользовательского представления для каждой ячейки в моем 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)

Что я мог делать не так?

Заранее спасибо.

1 Ответ

0 голосов
/ 11 апреля 2020

Добавьте slantedView в методе awakeFromNib () вместо 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
}
...