0

How can I make the border color of a UIView gradient?

I have declared a UIView from my storyboard and I know how to make the border color solid. But I can't find out how to make the border gradient.

 @IBOutlet weak var view: UIView! 

override func awakeFromNib() {
        super.awakeFromNib() 

    let gradient = CAGradientLayer()

    gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]

        view.backgroundColor = nil
        view.layer.cornerRadius = view.bounds.width / 2
        view.layer.borderWidth = 3
        view.layer.borderColor = colorOutline.cgColor


        nah.textColor = colorCircleBlue


    }
ILoveToCode22
  • 235
  • 1
  • 3
  • 12

2 Answers2

1

if you want make circular gradient frame try this:

 let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.yourView.frame.size)
    gradient.colors = [UIColor(red: 1, green: 0.2527923882, blue: 1, alpha: 1).cgColor, UIColor(red: 0.1802595352, green: 0.06151589641, blue: 0.2927506345, alpha: 1).cgColor]
    let shape = CAShapeLayer()
    shape.lineWidth = 2
    shape.path = UIBezierPath(roundedRect: yourView.bounds.insetBy(dx: 2, dy: 2), cornerRadius: yourView.frame.width * 0.5).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape
    self.yourView.layer.addSublayer(gradient)

your view must has 1 aspect ratio between height and weight // pink and purple color => [UIColor(red: 1, green: 0.2527923882, blue: 1, alpha: 1).cgColor, UIColor(red: 0.1802595352, green: 0.06151589641, blue: 0.2927506345, alpha: 1).cgColor]

Masoud Roosta
  • 455
  • 9
  • 19
0

Hello Whatsup

Below i put an example to you finish your task.

I put my code inside on didSet, but you can put also inside didLoad if you want.

I also don't know who do this, and i search and i discover this answer.

@gvuksic explain how create a border gradient on UIView us here

        let gradient = CAGradientLayer()
        gradient.frame =  CGRect(origin: CGPoint.zero, size: self.view.frame.size)
        gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]

        let shape = CAShapeLayer()
        shape.lineWidth = 2
        shape.path = UIBezierPath(rect: self.view.bounds).cgPath
        shape.strokeColor = UIColor.black.cgColor
        shape.fillColor = UIColor.clear.cgColor
        gradient.mask = shape

        self.view.layer.addSublayer(gradient)
Jackson Smith
  • 576
  • 4
  • 14