将 UILabel(行数设置为 0)及其下方的按钮添加到滚动视图。设置约束,使按钮在标签底部具有垂直间距约束。给标签一个固定的宽度约束和一个高度约束。为高度约束创建一个 IBOutlet,并使用从 sizeWithFont:constrainedToSize:lineBreakMode: 获得的值在代码中调整该约束的常量参数。您还需要使用相同的值加上适合按钮所需的大小来调整滚动视图的 contentSize。这将导致标签根据其包含的文本具有正确的高度,并且您的按钮将始终位于该标签下方的设定距离。
- (void)viewDidLoad {
[super viewDidLoad];
self.label.text = @"dfkl;jfjdfkjf sdfl klf;jskdl;fja skfjdklfj skdlfjs dklfjsklfj sklfjskl;f jks;alfjsk;lfjs;klfj;kfjs;kljk;lfjskdfj;klf j;klf jkl;fj;klfj;klfj k;fs;klfjsk;lfj ;klfjk;alfjk;alfjk;lfjk;lfjlkf kl;ajf akl;sfj sk;fk;lfjsk;ldfjsk;lfjsk;lfjsklfjkl;s fjklsafj kslfjkl fjklasfjklajfklafjaksdlfj lsdkf jsklfskl;f skld fjlk;sfklsfj ksff;kjdsfj sfkl;fkl;fklklfjlk;";
CGSize labelSize = [self.label.text sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(280, CGFLOAT_MAX)]; // 280 is the width of the label set in IB
self.heightCon.constant = labelSize.height;
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, labelSize.height +120);
}
In this example heightCon is the IBOutlet to the height constraint of the label made in IB. I did this in viewDidLoad, but you would need to do this wherever you populate your label with the text.