首页 > 解决方案 > 如何在表视图中为另一个表视图行的表视图行生成相同的随机颜色?

问题描述

在我的应用程序中,我单击一行,它会在其下方展开另一行。我想生成一种随机颜色,当我单击一行时,行背景会变成该颜色,而它下面的展开行会变成相同的颜色。如何让行生成相同的随机颜色?

我创建了一个函数来生成随机颜色,当 isOpened 设置为 true 时,我为行调用函数单元格,并为展开的单元格调用相同的函数。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
    let dataIndex = indexPath.row - 1  
    guard let cell1 = tableView.dequeueReusableCell(withIdentifier: "cell1") else {return UITableViewCell()}  

    func generateRandomColor() -> UIColor {  
        let redValue = CGFloat(drand48())  
        let greenValue = CGFloat(drand48())  
        let blueValue = CGFloat(drand48())  

        let randomColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)  

        return randomColor  
    }  

    if indexPath.row == 0 {  
        if tableViewData[indexPath.section].opened == false {  
            tableViewData[indexPath.section].opened = false  
            cell1.textLabel?.text = tableViewData[indexPath.section].title  
            cell1.textLabel?.numberOfLines = 0  
            cell1.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping  
            cell1.textLabel?.font = UIFont.systemFont(ofSize: 18)  
            cell1.backgroundColor = UIColor.clear  
            return cell1  
        }  
        else if tableViewData[indexPath.section].opened == true {  
            tableViewData[indexPath.section].opened = true  
            cell1.textLabel?.text = tableViewData[indexPath.section].title  
            cell1.textLabel?.numberOfLines = 0  
            cell1.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping  
            cell1.textLabel?.font = UIFont.boldSystemFont(ofSize: 25)  
            cell1.backgroundColor = generateRandomColor()  
            return cell1  
        }  
        return cell1  
    } else {  
        cell1.textLabel?.text = tableViewData[indexPath.section].sectionData[dataIndex]  
        cell1.textLabel?.numberOfLines = 0  
        cell1.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping  
        cell1.textLabel?.font = UIFont.systemFont(ofSize: 18)  
        cell1.backgroundColor = generateRandomColor()  
        return cell1  
    }  
}  

生成随机颜色,但展开的行生成新颜色。

标签: swiftxcodetableviewuicolor

解决方案


您将需要存储生成的随机颜色。每次调用 generateRandomColor() 时,都会创建一个新的。我要做的是创建一个行到颜色的字典。

var color: [Int: UIColor?] = [:]

然后在 cellForRowAtIndexPath 确定你是否已经有该行的颜色,如果没有计算一个:

if let color = colors[indexPath.row] {
    cell.backgroundColor = color
} else {
    colors[indexPath.row] = generateRandomColor()
}

然后在 didSelectRowForIndexPath 中,您可以使用以下方法检索 randomColor:

if let color = colors[indexPath.row] {
        // Expand the cell with the new color
}

推荐阅读