I am trying to insert UIViewController view into a horizontal UIStackView dynamically. The UIStackView is embedded in a UIScrollView.
Everything works well if I trying to add a label or a button in my stack view with the same approach commented in the code below. But when I try to insert the view controller's view, it fails to layout components correctly.
Here's my ViewController code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var stackview: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addComponents(_ sender: Any) {
let componentsView = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ComponentsView")
//componentsView.preferredContentSize = CGSize(width: 375, height: 200)
//let button = UIButton(type: .system)
//button.setTitle("Test", for: .normal)
stackview.insertArrangedSubview(componentsView.view, at: 1)
UIView.animate(withDuration: 0.5) {
self.stackview.layoutIfNeeded()
}
}
}
There is no warning on building nor during the execution.
Am I missing something?
Adding my observation regarding stack view, don't know it will work in this scenario or not.
if we are using stack view from storyboard and adding some view in it than we need to give height as a compulsory field. (Fill - Fill property).
try to give height of subview first before adding it. than it will work as expected