Search code examples
swiftuistackview

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

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)
        }
    }