这取决于您要动态添加的内容类型。所以假设你有一个大的文本数据要显示,然后使用UITextView,因为它是UIScrollView的子类,你可以在分配文本内容时获取TextView的setContentSize。基于此,您可以设置UIScrollView 的总大小。
float yPoint = 0.0f;
UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, yPoint, 320.0f, 400.0f)];
UITextView *calculatorTextView = [[UITextView alloc] init];
calculatorTextView.text = @"My looong content text ..... this has a dynamic content";
[calculatorTextView sizeToFit];
yPoint = yPoint + calculatorTextView.contentSize.height; // Bingo, we have the new yPoiny now to start the next component.
// 现在您知道了文本的高度和结束位置。因此,您可以创建一个 Label 或另一个 TextView 并在那里显示您的文本。您可以将这些组件作为子视图添加到滚动视图。
UITextView *myDisplayContent = [[UITextView alloc] initWithFrame:CGRectMake(0.0f, yPoint, 300.f, calculatorTextView.contentSize.height)];
myDisplayContent.text = @"My lengthy text ....";
[myScrollView addSubview:myDisplayContent];
//最后将'myScrollView'的内容大小设置为显示区域的总长度。
[myScrollView setContentSize:yPoint + heightOfLastComponent];
这对我有用。