在 Swift 4 中向 UILabel 文本添加渐变

Add Gradient to UILabel text in Swift 4

我正在尝试在 cellForRowAtIndexPath 方法的 table 视图单元格中向 UILabel 中的文本添加渐变,代码如下:

cell.cellLabel.textColor = UIColor(patternImage: UIImage(named: "gradientText"))

其中 "gradientText" 是所需渐变的 png 文件,textColor 是单元格中的 UILabel。但文本颜色仍然是默认颜色。我可以不使用任何第三方代码实现它吗?

引用

extension UILabel {
    func setTextColorToGradient(image: UIImage) {
        UIGraphicsBeginImageContext(frame.size)
        image.draw(in: bounds)
        let myGradient = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.textColor = UIColor(patternImage: myGradient!)
    }
}

你可以这样使用:

cell.cellLabel.setTextColorToGradient(image: UIImage(named: "gradientText")!)