LoginSignup
15
9

More than 5 years have passed since last update.

UIに破線のBorderを追加するExtension

Last updated at Posted at 2016-06-24

破線の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)
15
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9