【问题标题】:How to set different color for each TableViewCell?如何为每个 UITableViewCell 设置不同的颜色?
【发布时间】:2020-07-01 17:11:32
【问题描述】:

您好,我是 IOS 开发新手。我正在尝试为每个 tableview 单元格提供不同的十六进制颜色。以下更改 contentView 颜色的代码无济于事。

var cellColors = ["F28044","F0A761","FEC362","F0BB4C","E3CB92","FEA375"]

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomCells
        cell.contentView.backgroundColor = UIColor(named: cellColors[indexPath.row % cellColors.count])
    }

【问题讨论】:

  • 您能解释一下“以下代码更改 contentView 颜色没有帮助吗?”它怎么没有帮助?它在做什么是错的?你到底想让它做什么?在此处需要更多信息

标签: ios swift uitableview swift5


【解决方案1】:

您不能使用UIColor(named:) 加载HEX 颜色,您需要的是UIColor 的扩展,它可以采用字符串(十六进制)并返回UIColor

将此添加到您的代码库中:

extension UIColor {
    public convenience init?(hex: String) {
        let r, g, b, a: CGFloat

        if hex.hasPrefix("#") {
            let start = hex.index(hex.startIndex, offsetBy: 1)
            let hexColor = String(hex[start...])

            if hexColor.count == 8 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255

                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
}

像这样使用它:

let color = UIColor(hex: "#\(arrayItem)")

更多信息here

【讨论】:

    【解决方案2】:

    在您的 UIColor 扩展中添加以下方法,如下所示,并使用颜色代码初始化您的颜色。

    extension UIColor {
         public convenience init(_ value: Int) {
             let red = CGFloat(value >> 16 & 0xFF) / 255.0
             let green = CGFloat(value >> 8 & 0xFF) / 255.0
             let blue = CGFloat(value & 0xFF) / 255.0
             self.init(red: red, green: green, blue: blue, alpha: 1.0)
         }
    }
    

    你的方法是这样的:

    let color1 = UIColor(0xf123ac)
    let color2 = UIColor(0xF5B2C1)
    

    只需确保在您的颜色代码前加上 0x

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      相关资源
      最近更新 更多