首页 > 解决方案 > GradientLayer 与 Swift 中的单元格标签重叠?

问题描述

我想将我的单元格标签背景更改为渐变并将标签文本更改为白色。下图是 tableView,单元格标签如图所示重叠。

在此处输入图像描述

这是我下面的代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = self.tableView.dequeueReusableCell(
            withIdentifier: "tableViewCell",
            for: indexPath) as! CustomTableViewCell
  let bubbleGradient: CAGradientLayer = CAGradientLayer()

  let colorTop = UIColor(red:0.08, green:0.12, blue:0.19, alpha:1.0).cgColor
  let colorBottom = UIColor(red:0.14, green:0.23, blue:0.33, alpha:1.0).cgColor

  bubbleGradient.colors = [colorTop, colorBottom]
  bubbleGradient.startPoint = CGPoint(x: 0.0, y: 0.5)
  bubbleGradient.endPoint = CGPoint(x: 1.0, y: 0.5)

  bubbleGradient.frame = cell.text.bounds
  bubbleGradient.cornerRadius = 10
  cell.text.layer.addSublayer(bubbleGradient)
  cell.text?.text = text as? String

  return cell
}

但是 GradientLayer 与我的单元格标签重叠。我该如何解决?

标签: iosswiftcagradientlayer

解决方案


当您将子图层插入 UILabel 时,它将隐藏标签文本。因此,在 UIView 中添加 UIlabel 并将渐变应用到 UIView 的图层。检查以下代码:

let bubbleGradient: CAGradientLayer = CAGradientLayer()

let colorTop = UIColor(red:0.08, green:0.12, blue:0.19, alpha:1.0).cgColor
let colorBottom = UIColor(red:0.14, green:0.23, blue:0.33, alpha:1.0).cgColor

bubbleGradient.colors = [colorTop, colorBottom]
bubbleGradient.startPoint = CGPoint(x: 0.0, y: 0.5)
bubbleGradient.endPoint = CGPoint(x: 1.0, y: 0.5)

bubbleGradient.frame = label.bounds
label.backgroundColor = UIColor.clear
let viewLabel = UIView.init(frame: label.frame)
self.view.addSubview(viewLabel)
viewLabel.backgroundColor = UIColor.clear
viewLabel.addSubview(label)
bubbleGradient.cornerRadius = 10
viewLabel.layer.insertSublayer(bubbleGradient, at: 0)

在此处输入图像描述


推荐阅读