如何在SwiftUI中创建自定义单元格?其中每种单元格的颜色均来自特定的十六进制数字列表

问题描述 投票:-2回答:1

我有一个.txt列表,从中可以获取列表中每个单元格颜色的十六进制值。如何设置每个单元格的值?

我尝试使用ForEach循环在列表中进行迭代,但我真的不知道如何使用该循环。

这是我在UIKit版本中需要的代码(fromHexToColor()是UIColor扩展):

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
        let label: String = hexColorNames[indexPath.row]

        cell.cellLabel.text = label
        cell.backgroundColor = UIColor().fromHexToUIColor(hexColorNames[indexPath.row])

        return cell

    }

我期望列表内的整个单元格数组,其中每个单元格背景来自列表中的十六进制值。this is the UIKit version of the expected result

swift swiftui
1个回答
0
投票

这样的事情应该可以帮助您前进:

import SwiftUI

func hexStringToUIColor (hex:String) -> Color {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        return Color.gray
    }

    var rgbValue:UInt64 = 0
    Scanner(string: cString).scanHexInt64(&rgbValue)

    return Color(
        red: Double((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: Double((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: Double(rgbValue & 0x0000FF) / 255.0
    )
}

struct ContentView: View {
    let colors: [String] = ["#d3d3d3", "#7f7f7f", "#000000", "#FFFFFF"]

    var body: some View {
        List {
            ForEach(colors, id: \.self) { color in
                Text(color.description.capitalized)
                    .background(hexStringToUIColor(hex: color))
            }
        }.listRowInsets(EdgeInsets())
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.