UIScrollView中的多行UILabel

时间:2014-12-31 20:01:26

标签: ios uiscrollview uilabel

我无法在滚动视图中为标签创建多行。虽然它完全适用于滚动视图之外。有关详情,请参见下图。滚动视图具有水平滚动。

Image

UPD :ScrollView和标签约束:

enter image description here

1 个答案:

答案 0 :(得分:2)

显然我需要明确设置ScrollView contentSize。另外要获得这个尺寸,我需要从标签上知道它,这里有点棘手。完整的代码如下:

// create a label as usual
let label = UILabel()
label.numberOfLines = 0
label.text = "really long label text..."

// place it with a nice offset and set its width explicitly using parent view width
// after which `sizeToFit` does a trick and adjusts it's height
label.frame.offset(dx: 16.0, dy: 16.0)
label.frame.size.width = self.view.frame.width - 32
label.sizeToFit()

// now add it to the scroll view and set content size to label size plus margin at the bottom
self.scrollView.addSubview(label)
self.scrollView.contentSize = label.frame.size
self.scrollView.contentSize.height += 32