[iOS]View의 한 변(한쪽)에 점선을 그립니다.

13516 단어 iOStips
참고로

///利用側
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에 연동해주지 않기 때문에 교체가 귀찮네요.

좋은 웹페이지 즐겨찾기