UIStackView宽度和宽度高度不随着元素的添加而变化

时间:2018-06-03 15:17:40

标签: ios swift xcode uistackview

上下文

我正在尝试以编程方式创建UIStackView,但它根本没有显示。

为了测试,我创建了2个小UIView个,我添加到UIStackView

我试过

  • UIStackView
  • 添加约束
  • 使用layoutIfNeeded
  • 使用layoutSubviews

但没有任何效果。

代码

import UIKit

class ViewController: UIViewController {
    var contentStack = UIStackView()

    @IBOutlet weak var mainScroll: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        contentStack.backgroundColor = #colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1)
        contentStack.axis = .vertical
        contentStack.spacing = 0
        contentStack.alignment = .top
        contentStack.distribution = .equalSpacing

        let a_view = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 30))
        a_view.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
        contentStack.addArrangedSubview(a_view)

        let b_view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
        b_view.backgroundColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
        contentStack.addArrangedSubview(b_view)

        mainScroll.addSubview(contentStack)
        contentStack.topAnchor.constraint(equalTo: mainScroll.topAnchor).isActive = true
        contentStack.leftAnchor.constraint(equalTo: mainScroll.leftAnchor).isActive = true
        contentStack.bottomAnchor.constraint(equalTo: mainScroll.bottomAnchor).isActive = true
        contentStack.rightAnchor.constraint(equalTo: mainScroll.rightAnchor).isActive = true
        mainScroll.contentSize = CGSize(width: self.view.frame.width, height: contentStack.frame.height)

        print("Stack Content Size: (\(contentStack.frame.width), \(contentStack.frame.height))");
    }
}

输出

Output

问题

阅读文档后,我假设UIStackView的身高和高度宽度都适应视图添加后包含堆栈视图大小的元素,它是Stack Content Size: (0.0, 0.0)

1 个答案:

答案 0 :(得分:6)

尝试设置a_view和b_view的约束,如下所示

let a_view = UIView()
a_view.translatesAutoresizingMaskIntoConstraints = false
a_view.heightAnchor.constraint(equalToConstant: 30).isActive = true
a_view.widthAnchor.constraint(equalToConstant: 30).isActive = true

堆栈视图使用内在内容大小,因此使用布局约束来定义视图的维度。

如果这不起作用,那么我怀疑滚动视图约束可能存在一些问题。