Tom
Tom

Reputation: 4033

Apply CAGradientLayer to layer.borderColor

I'm trying to implement a underlined UITextField with a gradient. Therefore I created a extension with a function underlined().

To get a gradient, I created a CAGradientLayer and made these customizations:

func underlined(){
        let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1).cgColor
        let sndColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1).cgColor

        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.colors = [color, sndColor]
        gradient.locations = [0.0, 1.0]
        gradient.startPoint = CGPoint(x: 0, y: 0)
        gradient.endPoint = CGPoint(x: 1, y: 0)
        let width = CGFloat(2.0)
        gradient.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
        gradient.borderWidth = width

        self.layer.insertSublayer(gradient, at: 0)
        self.layer.masksToBounds = true
    }

A underline is being displayed, but it solely solid black - I've tried to change the colors, but it remains black (Issue outdated - see edit).

Does anybody see the issue?

Edit:
Adding gradient.borderColor = UIColor.blue.cgColor let me change the color of the line - but how can I apply the gradient on the border color?

Upvotes: 0

Views: 144

Answers (1)

PGDev
PGDev

Reputation: 24341

Remove the below line from your code:

gradient.borderWidth = width

Screenshot:

enter image description here

Your code was not working because, the borderWidth is covering whole of the gradient frame.Try setting the borderColor, then you'll see the difference.

gradient.borderColor = UIColor.red.cgColor

Let me know if you still face any issues.

Upvotes: 2

Related Questions