修复了UIStackview子视图的高度限制

时间:2017-04-29 01:35:11

标签: ios uiscrollview uikit nslayoutconstraint uistackview

我有UIScrollViewUIStackView子视图,称之为stack。我想在stack中拥有动态数量的子视图,但这些子视图将具有不同的高度。我怎样才能做到这一点?请注意,我试图回避故事板......

let scrollView = UIScrollView(frame: CGRect(x: 20, y: 20, width: view.frame.width - 20, height: view.frame.height - 20))
scrollView.center = view.center
self.view.addSubview(scrollView)


let stack = UIStackView(frame: CGRect(x: 20, y: 20, width: scrollView.frame.width - 40, height: scrollView.frame.height - 40))
stack.axis = .vertical
stack.alignment = .fill
stack.distribution = .fillProportionally
stack.spacing = 20
scrollView.addSubview(stack)

let label1 = UILabel()
label1.text = "This is going to be very, very long. I don't know how to make this guy longer. Words and words and more words. // Do any additional setup after loading the view, typically from a nib."
label1.numberOfLines = 0
label1.sizeToFit()

// Add more labels similar to label1

我尝试为每个UILabel子视图添加一个约束,但它并没有真正起作用。

let x = NSLayoutConstraint(item: label1, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: label1.frame.size.height)
label1.addConstraint(x)

请帮忙!感谢。

1 个答案:

答案 0 :(得分:0)

尝试更改堆栈视图的分发模式:

stack.distribution = .fillProportionally

(我不确定那是正确的一种,如果不只是尝试所有不同的分发模式:))