CollectionViewCell不会更改其背景颜色

时间:2019-09-18 18:12:03

标签: ios swift uicollectionview

我有一个集合视图,视图根据标志而变化,如果标志为1,则变为绿色,如果标志为0,则变为红色。但是它第一次渲染并没有改变,而是直到我滚动并返回。奇怪的是,它可以正确更改图标,文本,文本颜色等(在此代码中未显示),只是背景颜色没有变化!怎么了?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SensorCollectionViewCell", for: indexPath) as? SensorCell else {
            return UICollectionViewCell()
        }
        //Fill with data. 

        if sensors[indexPath.row]["alert"] as? Int == 0 {
            cell.alertState.textColor = UIColor.white
            cell.background.backgroundColor = UIColor(named: "Tomato")
            //more things 
        }

        if sensors[indexPath.row]["alert"] as? Int == 1 { 
            cell.alertState.textColor = UIColor.white
            cell.background.backgroundColor = UIColor(named: "KelleyGreen")
            //more things 
        }

        return cell
    }
import UIKit

class SensorCell: UICollectionViewCell {
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var sensorImage: UIImageView!
    @IBOutlet weak var sensorType: UILabel!
    @IBOutlet weak var sensorValue: UILabel!
    @IBOutlet weak var alertState: UILabel!
    @IBOutlet weak var background: UIView!
    @IBOutlet weak var bellIcon: UIImageView!


    static func loadFromNib() -> CardSensors {
        return Bundle.main.loadNibNamed("SensorCell", owner: nil, options: nil)?.first as! CardSensors
    }

    func roundCorners(view :UIView, corners: UIRectCorner, radius: CGFloat){
        let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        view.layer.mask = mask
    }

    //Permite que no se dupliquen los estilos cuando se hace scroll rapido
    override func prepareForReuse() {
        super.prepareForReuse()
        self.background.backgroundColor = UIColor(named: "Grey")
        self.alertState.textColor = UIColor(named: "BrownGrey")
        self.alertState.text = NSLocalizedString("notification_inactive", comment: "")
        self.bellIcon.image = UIImage(named: "bell_grey")
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        sensorImage.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) //Le da el color gris y el circulo gris de cada sensor
        sensorImage.layer.cornerRadius = 25.0
        self.roundCorners(view: background, corners: [.bottomLeft, .bottomRight], radius: 9.0)
    }
}

更新1

我尝试添加layoutSubviews()layoutIfNeeded()

单元正在更改,但不是第一次创建。

0 个答案:

没有答案