Swift 动态设置颜色集合视图标签背景颜色

Swift 动态设置颜色集合视图标签背景颜色,swift,Swift,我有以下实现,这是它所期望的。我想知道我应该如何处理相应标签的颜色。例如,我想将标签颜色设置为蓝色表示活动,绿色表示成功,红色表示拒绝 enum Status: Int, RawRepresentable, CustomStringConvertible { case active case success case rejected var description : String { switch self { case .active: r

我有以下实现,这是它所期望的。我想知道我应该如何处理相应标签的颜色。例如,我想将标签颜色设置为蓝色表示活动,绿色表示成功,红色表示拒绝

enum Status: Int, RawRepresentable, CustomStringConvertible {
  case active
  case success
  case rejected
  
  var description : String {
    switch self {
    case .active:
      return "Active"
    case .success:
      return "Success"
    case .rejected:
      return "Rejected"
    }
  }
}
ClassCollectionViewCell.swift

final class ClassCollectionViewCell : UICollectionViewCell {
  @IBOutlet weak var statusLabel: UILabel!
}
struct Courses: Codable {
  let status: String?
}
视图控制器

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClassCollectionViewCell.identifier, for: indexPath) as? ClassCollectionViewCell else { return UICollectionViewCell() }
  cell.statusLabel.text = classVM.getStatusText(atIndex: indexPath.row)
  return cell
}
视图模型

func getStatusText(atIndex index: Int) -> String {
  return courses[index].status ?? ""
}
课程。swift

final class ClassCollectionViewCell : UICollectionViewCell {
  @IBOutlet weak var statusLabel: UILabel!
}
struct Courses: Codable {
  let status: String?
}

理想情况下,您可以将
状态
传递给您的单元格,单元格将相应地更新自身。由于您使用的是ViewModels,因此也可以为您的单元格引入一个ViewModels。通过执行以下操作,您的单元格不知道模型,它被抽象到视图模型中

最终类ClassCollectionCellViewModel{
私人出租状态:状态
变量文本:字符串{
状态说明
}
var背景颜色:UIColor{
开关状态{
案件.现行:
返回,蓝色
成功案例:
返回,绿色
案例.驳回:
返回,红色
}
}
初始化(状态:status){
self.status=状态
}
}
现在让单元格根据视图模型中的数据进行相应的自我更新。您还可能希望刷新
prepareforuse()
上的内容。现在还可以将子视图设置为私有

final类ClassCollectionViewCell:UICollectionViewCell{
@IBOutlet私有弱var状态标签:UILabel!
var视图模型:ClassCollectionCellViewModel{
didSet{update(with:viewMolde)}
}
重写func prepareForReuse()函数{
super.prepareforeuse()
viewModel=nil
}
私有函数更新(使用viewModel:ClassCollectionCellViewModel?){
statusLabel.text=viewModel?.text
statusLabel.backgroundColor=viewModel?.backgroundColor???。清除
}
}
并从主viewModel中指定单元格viewModel,在主viewModel中对其进行初始化

func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{
guard let cell=collectionView.dequeueReusableCell(带有ReuseIdentifier:ClassCollectionViewCell.identifier,for:indexPath)作为?ClassCollectionViewCell else{return UICollectionViewCell()}
cell.viewModel=classVM.getCellViewModel(atIndex:indexath.row)
返回单元
}