Making UIProgressView Rounded corners

Umair Afzal picture Umair Afzal · Dec 2, 2016 · Viewed 13.7k times · Source

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 ?

Answer

ooops picture ooops · Mar 20, 2017

UIProgressView has two part, progress part and track part. If you use Reveal, you can see it only has two subviews. The progress view hierarchy is very simple. so...

Objective-C

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.progressView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.layer.masksToBounds = YES;
        obj.layer.cornerRadius = kProgressViewHeight / 2.0;
    }];
}

Swift (3, 4 and 5+)

override func layoutSubviews() {
    super.layoutSubviews()
    subviews.forEach { subview in
        subview.layer.masksToBounds = true
        subview.layer.cornerRadius = kProgressViewHeight / 2.0
    }
}

I admit subclass or extend progressView is the recommended way. In case of you don't want to do that for such a simple effect, this may do the trick. Keep the situation that Apple will change the view hierarchy, and something may go wrong in mind.