动态设置颜色collectionview标签背景色

时间:2021-01-26 23:30:02

标签: swift

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

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!
}

视图控制器

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 ?? ""
}

Courses.swift

struct Courses: Codable {
  let status: String?
}

1 个答案:

答案 0 :(得分:1)

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

final class ClassCollectionCellViewModel {

    private let status: Status

    var text: String {
        status.description
    }

    var backgroundColor: UIColor {
        switch status {
        case .active:
            return .blue
        case .success:
            return .green
        case .rejected:
            return .red
        }
    }

    init(status: Status) {
        self.status = status
    }

}

现在让单元格根据视图模型中的数据更新自身。您可能还想刷新 prepareForReuse() 上的内容。现在您还可以将子视图设为私有。

final class ClassCollectionViewCell: UICollectionViewCell {

    @IBOutlet private weak var statusLabel: UILabel!

    var viewModel: ClassCollectionCellViewModel? {
        didSet { update(with: viewMolde) }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        viewModel = nil
    }

    private func update(with viewModel: ClassCollectionCellViewModel?) {
        statusLabel.text = viewModel?.text
        statusLabel.backgroundColor = viewModel?.backgroundColor ?? .clear
    }

}

并从您的主视图模型中分配单元格视图模型,您在其中对其进行初始化。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClassCollectionViewCell.identifier, for: indexPath) as? ClassCollectionViewCell else { return UICollectionViewCell() }
    cell.viewModel = classVM.getCellViewModel(atIndex: indexPath.row)
    return cell
}