gpt4 book ai didi

ios - 使用 UITableView 单元格作为 UIView 并通过点击它来永久更改它的颜色(颜色源来自生成随机颜色的函数)

转载 作者:行者123 更新时间:2023-11-28 16:00:25 24 4
gpt4 key购买 nike

我想为 UITableView 单元分配操作,以便在点击它时使用生成随机 UIColor 的函数永久更改其颜色。

我是一个完全的初学者,找不到任何可以帮助我或我会理解的东西。我算不上 100% 的解决方案(不客气),但如果我能得到任何帮助让我走上正轨,我将非常感激。

下面是我给定 Controller 的代码(在教程的帮助下编写):

import UIKit

class FruitsTableViewController: UITableViewController {

func getRandomColor() -> UIColor{
//Generate between 0 to 1
let red:CGFloat = CGFloat(drand48())
let green:CGFloat = CGFloat(drand48())
let blue:CGFloat = CGFloat(drand48())

return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}


// MARK: - Table View data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"

return cell
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section)"
}

}

最佳答案

UITableView Delegate 下面写下你的类:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath:  IndexPath) {

let cell = tableView.cellForRowAtIndexPath(indexPath)
let color = getRandomColor()
cell.backgroundColor = color
cell.contentView.backgroundColor = color

}

当您重复使用单元格时,它可能会在滚动时再次改变颜色。

关于ios - 使用 UITableView 单元格作为 UIView 并通过点击它来永久更改它的颜色(颜色源来自生成随机颜色的函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41159029/

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