OGeek|极客世界-中国程序员成长平台

标题: ios - UIScrollView ContentSize.height 默认为 0.0000? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 02:32
标题: ios - UIScrollView ContentSize.height 默认为 0.0000?

我正在尝试使用 UIScrollView 创建动态表单,但我注意到当我使用 NSLog 时,我的 scrollView 的 contentSize.height = 0.00000 我构建了 scrollView Storyboard上屏幕的宽度和高度,其中包含元素。那么为什么它返回 0 呢? scrollView 中的所有元素都正确显示/运行。 scrollView 的 contentSize 是否总是默认为 0 我只需要设置它?



Best Answer-推荐答案


Yes 默认为 0。 您应该通过将所有 View 高度和它们之间的空间相加来设置 ScrollView 的内容大小,例如:

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
scrollView.backgroundColor = [UIColor blueColor];
[self.view addSubview:scrollView];

NSUInteger spaceBetweenLabels = 10;

UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
firstLabel.text = @"first label text";

UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, spaceBetweenLabels + firstLabel.frame.size.height, 300, 40)];
secondLabel.text = @"second label text";

[scrollView addSubview:firstLabel];
[scrollView addSubview:secondLabel];

CGSize fullContentSize = CGSizeMake(300, firstLabel.frame.size.height + secondLabel.frame.size.height + spaceBetweenLabels);

[scrollView setContentSize:fullContentSize];

当然,如果您的 ScrollView 高度高于内容大小高度,它就不会滚动,因为一切都在屏幕上。

关于ios - UIScrollView ContentSize.height 默认为 0.0000?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16321178/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4