gpt4 book ai didi

swift - 如何在 TableView 中为另一个 TableView 行的 TableView 行生成相同的随机颜色?

转载 作者:行者123 更新时间:2023-11-28 11:35:37 26 4
gpt4 key购买 nike

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

我创建了一个函数来生成随机颜色,当 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
}
}

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

最佳答案

您需要存储生成的随机颜色。每次调用 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
}

关于swift - 如何在 TableView 中为另一个 TableView 行的 TableView 行生成相同的随机颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com