这是从数组动态添加标签的 Swift 版本。
var previousLabelHeight: CGFloat = 0.0;
for dict in items {
let text: String = "Some text to display in the UILabel"
let size = heightNeededForText(text as NSString, withFont: UIFont.systemFontOfSize(15.0), width: scrollView.frame.size.width - 20, lineBreakMode: NSLineBreakMode.ByWordWrapping)
let newLabelHeight = previousLabelHeight + size;
let label = UILabel(frame: CGRectMake(0, newLabelHeight, 0, 0))
label.text = text
label.sizeToFit() // resize the width and height to fit the text
previousLabelHeight = newLabelHeight + 5 //adding 5 for padding
scroll.addSubview(label)
}
由于 sizeWithFont: ConstraintedToSize 已从 ios 7.0 中弃用,我们必须使用 NSString 中的 boundingRectWithSize 方法......
func heightNeededForText(text: NSString, withFont font: UIFont, width: CGFloat, lineBreakMode:NSLineBreakMode) -> CGFloat {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode
let size: CGSize = text.boundingRectWithSize(CGSizeMake(width, CGFloat.max), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle], context: nil).size//text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MA
return ceil(size.height);
}