StackView插入偏移问题

时间:2016-12-14 21:47:22

标签: ios swift layout uiviewcontroller uistackview

我正在尝试动态地将UIViewController视图插入到水平UIStackView中。 UIStackView嵌入在UIScrollView中。

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

所以这是我的布局: 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

建筑时和执行期间都没有警告。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

添加我对堆栈视图的观察,不知道它在这种情况下是否有效。

如果我们使用故事板中的堆栈视图并在其中添加一些视图,而不是将高度作为必填字段。 (填写 - 填写财产)。

在添加之前尝试先给出子视图的高度。而不是按预期工作