GradientLayer 在 Swift 中的单元格标签上重叠?

GradientLayer is overlapping on cell label in 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 重叠在我的单元格标签上。我该如何解决?

当您向 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)

如您所知,我们重复使用单元格。在您的代码中,您在视图中添加图层而不删除第一层。这造成了问题。

    if cell.textLabel?.layer.sublayers == nil {

        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)
    }

在您的 cellForRow 方法中试试这个。