【发布时间】:2019-01-14 14:37:32
【问题描述】:
在我的UITableViewCell 类中,我有一个配置cellViewColor 的函数。我有一个对象数组,根据一些字段,我确定 cellView 应该是灰色、红色还是绿松石色。当表格视图重用单元格时,它会以随机方式更改颜色。
class WidgetCell: UICollectionViewCell {
@IBOutlet weak var cellView: UIView!
@IBOutlet weak var mainValue: UILabel!
@IBOutlet weak var placeDetails: UILabel!
@IBOutlet weak var place: UILabel!
@IBOutlet weak var image: UIImageView!
func configureCell(entity: EntityModel) {
self.mainValue.text = entity.monitor?.value
self.placeDetails.text = entity.name
self.place.text = entity.name
self.cellView.applyGradient(withColours: setDeviceStateColor(deviceState: helper(entity: entity) ))
}
private func setDeviceStateColor(deviceState: DeviceState) -> [UIColor] {
switch deviceState {
case .alert:
return [UIColor.red, UIColor.red]
case .on:
return [Colors.lightTurcoazLIH, Colors.mediumTurcoazLIH]
case .off:
return [UIColor.lightGray,UIColor.darkGray]
}
}
extension UICollectionViewCell {
func helper(entity: EntityModel) -> DeviceState {
let state = entity.monitor?.state ?? false
let alert = entity.monitor?.alert ?? false
if state && alert {
return .alert
} else if state && alert == false {
return .on
} else {
return .off
}
}
与细胞的双端队列有关。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! WidgetCell
cell.configureCell(entity: favoriteDevices[indexPath.row])
return cell
}
我希望一切都清楚,并且我的解释是有道理的。
另外,这里是 applyGradient(withColors:)
func applyGradient(withColours colours: [UIColor]) {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = self.bounds
gradient.cornerRadius = 3
gradient.colors = colours.map { $0.cgColor }
gradient.startPoint = CGPoint.init(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint.init(x: 0.0, y: 1.0)
self.layer.insertSublayer(gradient, at: 0)
}
【问题讨论】:
-
你能提供
applyGradient(withColours:)方法的代码吗? -
只有颜色混用?
mainValue、placeDetail和place是否正确?如果是,可能是applyGradient多次设置后无法正常工作。 -
我已经更新了代码。只是颜色混合了,每次重复使用单元格时,颜色都不一样。感觉几乎是随机的。
标签: ios swift uitableview tableview cell