2016-12-14 108 views
0

我试图动态地将UIViewController视图插入水平UIStackView。 UIStackView嵌入在UIScrollView中。StackView插入偏移问题

如果我试图在我的堆栈视图中添加一个标签或一个按钮,并且在下面的代码中注释了相同的方法,那么一切正常。但是当我尝试插入视图控制器的视图时,它无法正确地布置组件。

因此,这里是我的布局: enter image description here

这里是我的ViewController代码:

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

这里的结果: enter image description here

上有建筑物,也不是在执行过程中没有任何警告。

我错过了什么吗?

回答

0

添加我关于堆栈视图的观察,不知道它会在这种情况下工作与否。

如果我们使用故事板的堆栈视图并添加一些视图,那么我们需要将高度作为必填字段。 (填充 - 填充属性)。

尝试在添加子视图之前首先给出子视图的高度。比它会按预期工作