0

How can I add a dashed line inside UIView?

My code:

let  path = UIBezierPath()

let  p0 = CGPointMake(CGRectGetMinX(view.bounds),
                              CGRectGetMidY(view.bounds))
path.moveToPoint(p0)

let  p1 = CGPointMake(CGRectGetMaxX(view.bounds),
                              CGRectGetMidY(view.bounds))
path.addLineToPoint(p1)

let  dashes: [ CGFloat ] = [ 16.0, 32.0 ]
path.setLineDash(dashes, count: dashes.count, phase: 0.0)

path.lineWidth = 8.0
path.lineCapStyle = .Butt
UIColor.magentaColor().set()
path.stroke()
view.setNeedsDisplay()

But it does not display anything.

I am getting this in the log:

CGContextSetLineDash: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
nirav
  • 573
  • 5
  • 20

3 Answers3

2

Try This.

let rect = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: 180, height: 180))//Set Height width as you want
let layer = CAShapeLayer.init()
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8)
layer.path = path.cgPath;
layer.strokeColor = UIColor(red: 205/255, green: 207/255, blue: 211/255, alpha: 1.0).cgColor; // Set Dashed line Color
layer.lineDashPattern = [7,7]; // Here you set line length
layer.backgroundColor = UIColor.clear.cgColor;
layer.fillColor = UIColor.clear.cgColor;
self.newView.layer.addSublayer(layer);  

Hope it will help!

Satachito
  • 5,838
  • 36
  • 43
Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
  • Omit the `.init`s for more concise code, e.g.: `let rect = CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width:180, height:180))` – Caleb Feb 20 '18 at 13:01
0

Use below code to add dashed line to your parent view.

for index in 0 ..< 10 {
  let frame : CGRect = CGRectMake(index*10,200,2,30)
  var subview : UIView = UIView(frame: frame)
  testView.backgroundColor = UIColor.gray
  testView.alpha=1.0
  self.view.addSubview(testView)
}
0

This worked for me, I created a box and gave a height of e.g. 1 and added a dashed CAShapeLayer:

let line = CAShapeLayer()

let rect = CGRect(x: /*X position*/, y: /*Y position */, width: /*X width of line*/, height: /*height of line*/)

line.path = UIBezierPath(roundedRect: view.bounds, cornerRadius:0).cgPath
line.frame = self.bounds
line.strokeColor = UIColor.lightGray.cgColor
line.fillColor = UIColor.lightGray.cgColor
line.lineDashPattern = [4, 4]
view.layer.addSublayer(line)

Hope that helps!!

Agent Smith
  • 2,873
  • 17
  • 32