Skip to content

Instantly share code, notes, and snippets.

@fhefh2015
Created June 24, 2021 02:03
Show Gist options
  • Save fhefh2015/96f02d82eb9546c4b51eb79c51d33846 to your computer and use it in GitHub Desktop.
Save fhefh2015/96f02d82eb9546c4b51eb79c51d33846 to your computer and use it in GitHub Desktop.
CustomDashedView
//
// DashedBorderView.swift
// AInOne
//
// Created by Apple on 2021/6/23.
//
import UIKit
class DashedBorderView: UIView {
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var dashWidth: CGFloat = 0
@IBInspectable var dashColor: UIColor = .clear
@IBInspectable var dashLength: CGFloat = 0
@IBInspectable var betweenDashesSpace: CGFloat = 0
@IBInspectable var isAnimate: Bool = true
@IBInspectable var duration: Double = 0.5
var dashBorder: CAShapeLayer?
override func layoutSubviews() {
super.layoutSubviews()
dashBorder?.removeFromSuperlayer()
let dashBorder = CAShapeLayer()
dashBorder.lineWidth = dashWidth
dashBorder.strokeColor = dashColor.cgColor
dashBorder.lineDashPattern = [dashLength, betweenDashesSpace] as [NSNumber]
dashBorder.frame = bounds
dashBorder.fillColor = nil
if cornerRadius > 0 {
dashBorder.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
} else {
dashBorder.path = UIBezierPath(rect: bounds).cgPath
}
if isAnimate {
let lineDashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
lineDashAnimation.fromValue = 0
lineDashAnimation.toValue = dashBorder.lineDashPattern?.reduce(0) { $0 + $1.intValue }
lineDashAnimation.duration = duration
lineDashAnimation.repeatCount = Float.greatestFiniteMagnitude
dashBorder.add(lineDashAnimation, forKey: nil)
}
layer.addSublayer(dashBorder)
self.dashBorder = dashBorder
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment