Search code examples
iosswift2cgrect

How to change border style of CGRect in Swift2?


I'm learning Swift and my designer has given me a screen like this.

enter image description here

I am facing problem in how to change the border style of total credits CGRect in this dashed form.

My code is:

override func viewDidLoad()
{
    let promobox =  UIView()

    promobox.frame = CGRectMake(16, promotextfield.frame.minY + 180, self.view.frame.width - 32, 60)
    promobox.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).CGColor
    promobox.layer.borderWidth = 2.0
    promobox.layer.backgroundColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.2).CGColor

    //background color of box
    self.view.addSubview(promobox)
}

Solution

  • This is how you can do this:

    let promobox =  UIView()
    
    promobox.frame = CGRectMake(16, 50, self.view.frame.width - 32, 60)
    promobox.layer.borderColor = UIColor.whiteColor().CGColor
    promobox.layer.borderWidth = 2.0
    promobox.layer.backgroundColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.2).CGColor
    
    let border = CAShapeLayer.init()
    border.frame = promobox.bounds
    border.path = UIBezierPath(rect: border.frame).CGPath
    border.lineWidth = 2
    border.strokeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).CGColor
    border.fillColor = UIColor.clearColor().CGColor
    border.lineDashPattern = [4, 6]
    promobox.layer.addSublayer(border)
    

    Play with lineDashPattern to meet your designer's expectations.