ios - 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 与我的单元格标签重叠。我该如何解决?
解决方案
当您将子图层插入 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)
推荐阅读
- ios - Swift:将 ISO8601 转换为日期
- python-3.x - 捕获所有文本直到下一次出现,包括正则表达式中的换行符(Python 3.x)
- json - 在 Powershell 中过滤 JSON
- python - 如何在python中减去两个图像?
- c# - 将浮点数四舍五入为 int 作为具有小数阈值的字符串
- c++ - 有谁知道为什么在开关内使用 stoi 函数会返回不断的错误?
- scala - java.lang.NoClassDefFoundError:无法在scala spark中初始化类XXXXXXXX
- javascript - 如何根据类别填充子类别
- json - 重命名 Json 数组数据中的重复键
- python - 如何在根窗口 tkinter 中获取不同的窗口