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

标签 swift uitableview swift2 background-color uicolor

我有一个应用程序测验应用程序分为不同的类别。类别可以在 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/

相关文章:

ios - 如何在 iOS 图表上正确显示底轴 (xVals) 上的标签?

ios - UITableView 崩溃无法识别的选择器发送到实例

ios - 旋转时是否需要更新 TableView 布局?

ios - 如何使用 MRCountryPickerDelegate

ios - 如何从 swift(iOS) 重定向 Skype 应用程序

ios - 对成员 Swift 3 的模糊引用

objective-c - swift 2 : no delegate callbacks for push notifications as opposed to objective-c

ios - Swift UICollectionView 不以编程方式设置数据源和委托(delegate)

ios - 使用 UserRecordID 获取 CloudKit 用户记录

iphone - [self.tableView reloadData] 处的 EXC_BAD_ACCESS