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

时间:2018-05-04 08:57:18

标签: ios swift cagradientlayer

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

enter image description here

以下是我的代码

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与我的细胞标签重叠。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

当您将子图层插入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)

enter image description here

答案 1 :(得分: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方法中尝试此操作。