Pisan
Pisan

Reputation: 69

Change height of UIProgressView (Bar style) in Swift

I created a UIProgressView (bar style) in Swift 2.2 and would now like to alter its height. Some other posts suggested to use CGAffineTransformScale to change the height. However, for some reason this approach doesn't seem to work, as it does not have any effect on the height of the UIProgressView.

Below you will find my code:

let progressBar = UIProgressView(progressViewStyle: .Bar)
progressBar.progress = 0.5
progressBar.translatesAutoresizingMaskIntoConstraints = false
progressBar.transform = CGAffineTransformScale(progressBar.transform, 1, 20)
self.navigationItem.titleView = progressBar

I appreciate your help, thanks a lot!

Upvotes: 0

Views: 8833

Answers (1)

aircraft
aircraft

Reputation: 26896

You can subclass UIProgressView, and add a height property:

The result:

enter image description here

import UIKit

class CustomProgressView: UIProgressView {

    var height:CGFloat = 1.0 
    // Do not change this default value, 
    // this will create a bug where your progressview wont work for the first x amount of pixel. 
    // x being the value you put here.

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let size:CGSize = CGSize.init(width: self.frame.size.width, height: height)

        return size
    }

}

In the vc, you initial the customProgressvView, and set the height:

import UIKit

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let progressBar = CustomProgressView(progressViewStyle: .bar)
        progressBar.progress = 0.5
        progressBar.height = 10.0
        self.navigationItem.titleView = progressBar

    }
}

Upvotes: 6

Related Questions