Swift iOS: установить градиентный фон в UITextView?

Я пытаюсь применить градиентный фон к объекту UITextView, но не уверен, что это возможно, потому что вместо этого я получаю белый фон.

Вот мое расширение UIView:

extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}

Вот где я назначаю градиент для текстового представления:

        detailTxtView.translatesAutoresizingMaskIntoConstraints = false
    detailTxtView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    detailTxtView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
    detailTxtView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    detailTxtView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true

    detailTxtView.setTextGradient(startColor: Constants.Colors.bluLight, endColor: Constants.Colors.silver)

    // Set up text
    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont(name: "Jazeel-Bold", size: 24)!, NSForegroundColorAttributeName: Constants.Colors.bluLight])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont(name: "HacenTunisia", size: 20)!, NSForegroundColorAttributeName: Constants.Colors.aluminum]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    detailTxtView.attributedText = attributedTxt

Вот цвета в классе констант:

    struct Colors{ 
    static let bluDark      = UIColor(colorLiteralRed: 51/255, green: 50/255, blue: 80/255, alpha: 1)
    static let bluLight     = UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)
    static let greenLight   = UIColor(colorLiteralRed: 200/255, green: 255/255, blue: 132/255, alpha: 1)
    static let mercury      = UIColor(colorLiteralRed: 235/255, green: 235/255, blue: 235/255, alpha: 1)
    static let silver       = UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1)
    static let magnesium    = UIColor(colorLiteralRed: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    static let aluminum     = UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)
    static let blu2         = UIColor(colorLiteralRed: 88/255, green: 120/255, blue: 166/255, alpha: 0.2)
    static let bluLighter = #colorLiteral(red: 0.451, green: 0.5569, blue: 0.8314, alpha: 1) /* #738ed4 */
}

Я всегда получаю белый фон при использовании метода градиента. Ценю любые предложения.

4 ответа

Решение

Градиент работал, когда я установил его после установки атрибутов текста

detailTxtView.attributedText = attributedTxt
detailTxtView.setTextGradient(startColor: Constants.Colors.silver, endColor: Constants.Colors.bluDark)

Я думаю, что вы забыли местоположение

extension UIView
{
   func setGradient(startColor:UIColor,endColor:UIColor)
    {
        let gradient:CAGradientLayer = CAGradientLayer()
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.frame = self.bounds
        self.layer.insertSublayer(gradient, at: 0)
     }
}

использование

txtView.setGradient(startColor: UIColor.blue, endColor: UIColor.green)

Выход:

Вам нужно использовать locations собственностью CAGradientLayer

extension UIView{

    func setGriadientBackrnd(color1: UIColor, color2: UIColor){
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = [color1.cgColor, color2.cgColor]
        gradientLayer.locations = [0.5 , 0.5] //here you can set percentage of color part are display betwin 0 to 1
        layer.insertSublayer(gradientLayer, at: 0)
    }
}

Пожалуйста, проверьте ваш код Вывод

Привет, народ, попробуй так, надеюсь, ты поможешь,

    let titleStr = "Hi How are you ?"
    let detailStr = "HI How UR preparation..."
    gradientTextview.translatesAutoresizingMaskIntoConstraints = false
    gradientTextview.bottomAnchor.constraint(equalTo:self.view.bottomAnchor).isActive = true
    gradientTextview.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -8).isActive = true
    gradientTextview.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 8).isActive = true
    gradientTextview.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.5).isActive = true

    gradientTextview.setGradient(startColor: UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1), endColor: UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1))


    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont (name: "HelveticaNeue-Bold", size: 20)! , NSForegroundColorAttributeName: UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont (name: "HelveticaNeue-Bold", size: 18)! , NSForegroundColorAttributeName:UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.characters.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    gradientTextview.attributedText = attributedTxt

================================================== =============

extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}

НОТА:-

вместо просмотра вы можете добавить self.gradientTextview также...

Другие вопросы по тегам