Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't add UIProgressView in StackView

According to this code, I need to add 4 UIProgressViews to the StackView, but only 1 UIProgressView is added to the StackView. I am using Horizontal StackView.

enter image description here

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code:

class ViewController: UIViewController {
  
  @IBOutlet weak var imageView: UIImageView!
  @IBOutlet weak var stackView: UIStackView!
  
  var progressView: UIProgressView = {
    var view = UIProgressView()
    view.tintColor = .white
    view.progress = 0.5
    return view
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    for _ in 1...4 {
      stackView.addArrangedSubview(progressView)
    }
  }
}

>Solution :

You’re adding the same UIProgressView four times. But when you add a subview to a view, the subview is first removed from its existing superview, because a subview can only have a single superview and can only occupy a single slot in its superview’s subviews array.

You need to create four UIProgressViews.

let progressViews: [UIProgressView] = (0 ..< 4).map { _ in
    let view = UIProgressView()
    view.tintColor = .white
    view.progress = 0.5
    return view
}

override func viewDidLoad() {
    super.viewDidLoad()

    for progressView in progressViews {
        stackView.addArrangedSubview(progressView)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading