为什么不使用自动布局,这样可以支持设备的方向变化。
var lastLabel:UILabel?
for i in 0..<10servicesLength
{
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints=false
label.lineBreakMode = .ByWordWrapping
label.numberOfLines = 10
label.font = UIFont(name: label.font.fontName, size: 25)
label.text = servicesList[i]
servicesScroll.addSubview(label)
let metrics=["horizontalMargin":21,"top":0,"bottom":0,"separationBetweenLabels":0,"labelMinHeight":25]
let views=["label":label]
servicesScroll.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-horizontalMargin-[label]-horizontalMargin-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
if i == 0{
servicesScroll.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-top-[label]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
}
if let lastLabel=lastLabel{
views["lastLabel"]=lastLabel
servicesScroll.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[lastLabel]-separationBetweenLabels-[label]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
}
if i == (servicesLength-1){
servicesScroll.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[label]-bottom-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
}
servicesScroll.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[label(>=labelMinHeight)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
lastLabel=label
}
重要的是,您需要将每个标签的numberOfLines设置为允许标签增长的最大尺寸。
另外,我添加了一个最小高度的约束:
//Optional a minimum height of 25
servicesScroll.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[label(25)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: metrics,
views: views))
在这个例子中,这将确保标签的高度至少为25,并且最多有10行。