参考までに
///利用側
func _() {
hogeView.addOneSideDashBorder(position: .bottom, color: .red, lineDashPattern: [5, 5])
}
extension UIView {
/// 一辺に点線を引く
@discardableResult
func addOneSideDashBorder(position: BorderPosition, color: UIColor, lineDashPattern: [NSNumber]?) -> CALayer {
layoutIfNeeded()
let shapeLayer = CAShapeLayer()
shapeLayer.lineDashPattern = lineDashPattern
shapeLayer.strokeColor = color.cgColor
shapeLayer.frame = bounds
let line = UIBezierPath()
switch position {
case .top:
line.move(to: bounds.leftTop)
line.addLine(to: bounds.rightTop)
case .left:
line.move(to: bounds.leftTop)
line.addLine(to: bounds.leftBottom)
case .right:
line.move(to: bounds.rightTop)
line.addLine(to: bounds.rightBottom)
case .bottom:
line.move(to: bounds.leftBottom)
line.addLine(to: bounds.rightBottom)
}
shapeLayer.path = line.cgPath
layer.addSublayer(shapeLayer)
return shapeLayer
}
}
/// 上下左右
enum BorderPosition {
case top
case left
case right
case bottom
}
///
extension CGRect {
var leftTop: CGPoint {
return CGPoint(x: 0, y: 0)
}
var rightTop: CGPoint {
return CGPoint(x: width-1, y: 0)
}
var leftBottom: CGPoint {
return CGPoint(x: 0, y: height-1)
}
var rightBottom: CGPoint {
return CGPoint(x: width-1, y: height-1)
}
}
結果
考えたら実線もこっちでいいのではないでしょうか?
borderを使う方法のほうが一般的ですが、ソッチのほうがいい理由はあるのか(ちょっとわかりません)
extension UIView {
/// 一辺に実践を引く
@discardableResult
func addOneSideBorder(position: BorderPosition, color: UIColor) -> CALayer {
layoutIfNeeded()
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = 1
shapeLayer.frame = bounds
let line = UIBezierPath()
switch position {
case .top:
line.move(to: bounds.leftTop)
line.addLine(to: bounds.rightTop)
case .left:
line.move(to: bounds.leftTop)
line.addLine(to: bounds.leftBottom)
case .right:
line.move(to: bounds.rightTop)
line.addLine(to: bounds.rightBottom)
case .bottom:
line.move(to: bounds.leftBottom)
line.addLine(to: bounds.rightBottom)
}
shapeLayer.path = line.cgPath
layer.addSublayer(shapeLayer)
return shapeLayer
}
}
追記:欠点見つけました。borderと違い、Viewのframeに連動してくれないので付け替えが面倒ですね。