Search code examples
iosswiftuiprogressview

How to create Vertical Progress Bar - IOS - Swift


I am trying to create a vertical progress bar. But the problem is my code is working on IOS11 or Above but on IOS9 it's not working.

On IOS11 Or Above it looks like: enter image description here

But on IOS9 it looks like: enter image description here

My Code:

let progressBar: UIProgressView = {
    let prgressView = UIProgressView()
    prgressView.progress = 0.7
    prgressView.progressTintColor = UIColor(red: 1.0, green: 0.21, blue: 0.33, alpha: 1)
    prgressView.trackTintColor = UIColor.blue
    prgressView.layer.cornerRadius = 6.5
    prgressView.clipsToBounds = true
    prgressView.transform = CGAffineTransform(rotationAngle: .pi / -2)
    prgressView.translatesAutoresizingMaskIntoConstraints = false
    return prgressView
}()

layoutSubview()

override func layoutSubviews() {
    super.layoutSubviews()

    let width = progressBar.bounds.width
    let height = progressBar.bounds.height

    progressBar.bounds.size.width = height
    progressBar.bounds.size.height = width
}

viewDidLoad()

    self.addSubview(progressBar)
    progressBar.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    progressBar.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    progressBar.widthAnchor.constraint(equalToConstant: 22.5).isActive = true
    progressBar.heightAnchor.constraint(equalToConstant: 250).isActive = true

I am following this tutorial to create vertical progressView: https://www.youtube.com/watch?v=ifekgTtb0rQ&t=1070s


Solution

  • I was able to make your code work just fine under iOS 9 and iOS 12 by making two changes to the code you posted:

    1. Remove layoutSubviews. You have set constraints. Do not also attempt to modify the view's frame directly.
    2. Swap the width and height constraints. Think about the size of the progress bar if you didn't apply the transform. You want the width to be 250 and the height to be 22.5. The transform doesn't change this. The transform only makes it look like it's 250 tall but it is still 250 wide.

    In short, remove layoutSubviews and fix your constraints to:

    progressBar.widthAnchor.constraint(equalToConstant: 250).isActive = true
    progressBar.heightAnchor.constraint(equalToConstant: 22.5).isActive = true