Search code examples
iosswiftuiprogressview

Making UIProgressView Rounded corners


I have created a UIProgressView with following properties

progressView.progressTintColor = UIColor.appChallengeColorWithAlpha(1.0)
progressView.trackTintColor = UIColor.clearColor()
progressView.clipsToBounds = true
progressView.layer.cornerRadius = 5

I am using a UIView for border. It appears like his progress = 1, which is exactly the way I want.

enter image description here

But if progress value is less then 1. Corners are not rounded as it should be.

enter image description here

Am I missing something ? How can I make it rounded corner ?


Solution

  • After searching and trying I decided to create my own custom progress view. Here is the code for anyone who may find them selevs in same problem.

    import Foundation
    import UIKit
    
    class CustomHorizontalProgressView: UIView {
    var progress: CGFloat = 0.0 {
    
        didSet {
            setProgress()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    
        setup()
    }
    
    func setup() {
        self.backgroundColor = UIColor.clearColor()
    }
    
    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
    
        setProgress()
    }
    
    func setProgress() {
        var progress = self.progress
        progress = progress > 1.0 ? progress / 100 : progress
    
        self.layer.cornerRadius = CGRectGetHeight(self.frame) / 2.0
        self.layer.borderColor = UIColor.grayColor().CGColor
        self.layer.borderWidth = 1.0
    
        let margin: CGFloat = 6.0
        var width = (CGRectGetWidth(self.frame) - margin)  * progress
        let height = CGRectGetHeight(self.frame) - margin
    
        if (width < height) {
            width = height
        }
    
        let pathRef = UIBezierPath(roundedRect: CGRect(x: margin / 2.0, y: margin / 2.0, width: width, height: height), cornerRadius: height / 2.0)
    
        UIColor.redColor().setFill()
        pathRef.fill()
    
        UIColor.clearColor().setStroke()
        pathRef.stroke()
    
        pathRef.closePath()
    
        self.setNeedsDisplay()
    }
    }
    

    Just put above code in a swift file and drag drop a UIView in IB and give it class CustomHorizontalProgressView. and That is it.