Skip to content

Instantly share code, notes, and snippets.

@OksanaFedorchuk
Created April 21, 2021 14:05
Show Gist options
  • Save OksanaFedorchuk/d5e615e701a60d44d23def74ff35e94d to your computer and use it in GitHub Desktop.
Save OksanaFedorchuk/d5e615e701a60d44d23def74ff35e94d to your computer and use it in GitHub Desktop.
Horizontal and vertical progress bar
import UIKit
class ProgressBar: UIView {
// MARK: - Properties
@IBInspectable var color: UIColor = .gray {
didSet { setNeedsDisplay() }
}
var progress: CGFloat = 0 {
didSet { setNeedsDisplay() }
}
var isHorisontal: Bool = true {
didSet { setNeedsDisplay() }
}
private let progressingLayer = CALayer()
private let backgroundMask = CAShapeLayer()
// MARK: - Initializer
override init(frame: CGRect) {
super.init(frame: frame)
addLayers()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addLayers()
}
// MARK: - Methods
private func addLayers() {
layer.addSublayer(progressingLayer)
}
override func draw(_ rect: CGRect) {
backgroundMask.path = UIBezierPath(roundedRect: rect, cornerRadius: rect.height * 0.25).cgPath
layer.mask = backgroundMask
var progressRect = CGRect()
if isHorisontal {
progressRect = CGRect(origin: .zero, size: CGSize(width: rect.width * progress, height: rect.height))
} else {
progressRect = CGRect(origin: .zero, size: CGSize(width: rect.width, height: rect.height * progress))
}
progressingLayer.frame = progressRect
progressingLayer.backgroundColor = color.cgColor
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment