gpt4 book ai didi

swift - 使 UITableViewCell 着色为特定百分比

转载 作者:行者123 更新时间:2023-11-28 08:19:01 25 4
gpt4 key购买 nike

我有一个应用程序测验应用程序分为不同的类别。类别可以在 UITableView 中看到,例如A 类、B 类、C 类...等。我试图通过为类别 UITableView 单元格的背景着色来显示已回答的问题的百分比作为 UITableView 中的视觉表示。

例如,如果此人完成了类别 A 中 75% 的问题,我希望 UITableView 中类别 A 的背景从左到右以绿色着色,占 Cell 背景的 75%。

知道如何做的唯一方法是制作绿色背景的背景图像,并根据回答问题的百分比将相关背景图像作为单元格背景的背景。

有没有更简单的方法?我可能会用类似的东西

Cell.backgroundcolor = UIColor.greencolor().75%ofCell.

我知道这段代码不正确,但它有点理解我正在尝试做的事情。

最佳答案

我认为您可以在不使用图层向单元格添加 View 的情况下做到这一点:

在您的单元格类中,您可以添加以下函数:

func addGradientLayer(percentage: Double) {
let color1 = UIColor.green
let color2 = UIColor.clear

let gradientLayer = CAGradientLayer()
// sets the gradient frame as the bounds of your cell
gradientLayer.frame = bounds

gradientLayer.colors = [color1.cgColor, color2.cgColor]

// tells the gradient to go from left to right
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

//this line is the important one: as
//long the second Double is smaller than
//your percentage, you will not get a gradient
//but a clear separation between your two colors.
gradientLayer.locations = [percentage, 0.0]

layer.addSublayer(gradientLayer)
}

然后您可以在 awakeFromNib() 方法或 cellForRowAt(tableView 委托(delegate))中调用此方法:

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.addGradientLayer(percentage: 0.8)
}

关于swift - 使 UITableViewCell 着色为特定百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41763008/

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