More than 1 year has passed since last update.

破線のBorderを追加するExtensionです。

UIView+drawDashedLine.swift

import UIKit

enum DashedLineType {
    case All,Top,Down,Right,Left
}

extension UIView {

    func drawDashedLine(color: UIColor, lineWidth: CGFloat, lineSize: NSNumber, spaceSize: NSNumber, type: DashedLineType) -> UIView {
        let dashedLineLayer: CAShapeLayer = CAShapeLayer()
        dashedLineLayer.frame = self.bounds
        dashedLineLayer.strokeColor = color.CGColor
        dashedLineLayer.lineWidth = lineWidth
        dashedLineLayer.lineDashPattern = [lineSize, spaceSize]
        let path: CGMutablePath = CGPathCreateMutable()

        switch type {

        case .All:
            dashedLineLayer.fillColor = nil
            dashedLineLayer.path = UIBezierPath(rect: dashedLineLayer.frame).CGPath
        case .Top:
            CGPathMoveToPoint(path, nil, 0.0, 0.0)
            CGPathAddLineToPoint(path, nil, self.frame.size.width, 0.0)
            dashedLineLayer.path = path
        case .Down:
            CGPathMoveToPoint(path, nil, 0.0, self.frame.size.height)
            CGPathAddLineToPoint(path, nil, self.frame.size.width, self.frame.size.height)
            dashedLineLayer.path = path
        case .Right:
            CGPathMoveToPoint(path, nil, self.frame.size.width, 0.0)
            CGPathAddLineToPoint(path, nil, self.frame.size.width, self.frame.size.height)
            dashedLineLayer.path = path
        case .Left:
            CGPathMoveToPoint(path, nil, 0.0, 0.0)
            CGPathAddLineToPoint(path, nil, 0.0, self.frame.size.height)
            dashedLineLayer.path = path

        }
        self.layer.addSublayer(dashedLineLayer)
        return self
    }
}

こんな感じで使ってください。

hogeLabel.drawDashedLine(UIColor.blueColor(), lineWidth: 2, lineSize: 3, spaceSize: 3, type: .All)