【问题标题】:Make a UITableViewCell Coloured to specific percentage将 UITableViewCell 着色为特定百分比
【发布时间】:2017-01-20 11:49:32
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

  • 你能给我们看看设计吗?你到底想要什么/

标签: swift uitableview swift2 background-color uicolor


【解决方案1】:

我认为您可以通过使用图层而不向单元格添加视图来做到这一点:

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

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 委托)中调用此方法:

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

【讨论】:

    【解决方案2】:

    假设您使用的是故事板,请在单元格中添加 UIViewbackgroundColor = .greenColor()

    为与父视图相等的视图添加顶部、左侧和底部约束,然后为视图添加宽度约束并为其创建一个出口。

    然后在单元格中你可以说:

    var pctScore: CGFloat {
       didSet {
           let viewWidth = cell.contentView.frame.width * pctScore
           widthConstraint.constant = viewWidth
       }
    }
    

    【讨论】:

      【解决方案3】:

      您可以将 UIView 作为子视图添加到单元格中,并将 UIView 的背景颜色设置为您想要的颜色。

      在添加视图之前,您将视图宽度设置为 0.75 * cellWidth。

      【讨论】:

        猜你喜欢
        • 2010-11-12
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 2021-05-19
        • 2021-12-12
        • 2016-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多