Search code examples
iosswiftuislideruiprogressviewuiprogressbar

Constraints for progress bar and label together in IOS Swift


I need to show a progress bar and a label adjacent to each other horizontally based on some condition and based on a different condition, I need to show label and progress bar one below the other vertically. Third condition is I hide the label and show only the progress bar. For the third condition, I want the progress bar to occupy the full width of the screen - some space on either end of it. Initially, I started by putting constraints to show them side by side and it worked. However, for the other two conditions when I try to modify existing constraints during run time, it is messing up and not working as expected. Any pointers on how the constraints should look like for these scenarios. Attached is an image of a progress bar and label side by sideenter image description here


Solution

  • Add a horizontal UIStackview and add a UIProgressView and a UILabel. Set label text alignment to center.

    Add top, bottom, leading, trailing constraints to the stackview. Don't add height constraint to the stackview. Add height constraint to the label.

    Change stackview configuration as

    enter image description here

    And change the styles by changing stackview's axis and hiding/showing the label as follows

    @IBAction func style1(_ sender: Any) {
        stackView.axis = .horizontal
        stackView.alignment = .center
        label.isHidden = false
    }
    @IBAction func style2(_ sender: Any) {
        stackView.axis = .vertical
        stackView.alignment = .fill
        label.isHidden = false
    }
    @IBAction func style3(_ sender: Any) {
        stackView.axis = .horizontal
        stackView.alignment = .center
        label.isHidden = true
    }
    

    enter image description here