我正在尝试构建一个具有多个不同控件的视图,但我希望该视图仅在垂直方向上滚动。我正在使用自动布局,所以我不想手动指定大小(我知道我可以做到这一点,但根据我对发布说明的理解,UIScrollView
你不应该这样做)。
因此,如果我创建一个简单的视图控制器(没有 .xib 文件)并简单地将以下内容添加到init
方法中,我希望我的标签会换行(他们会这样做)并且我的视图会垂直滚动,但是,这不是案子:
- (id)init {
self = [super init];
if (self) {
UIScrollView *_scrollView = [UIScrollView new];
[_scrollView setTranslatesAutoresizingMaskIntoConstraints:NO];
UILabel *label1 = [UILabel new];
UILabel *label2 = [UILabel new];
[label1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[label2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[label1 setNumberOfLines:0];
[label2 setNumberOfLines:0];
[label1 setPreferredMaxLayoutWidth:240];
[label2 setPreferredMaxLayoutWidth:240];
NSString *sampleText = @"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
[label1 setText:sampleText];
[label2 setText:sampleText];
[self.view addSubview:_scrollView];
[_scrollView addSubview:label1];
[_scrollView addSubview:label2];
NSArray *constraints;
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_scrollView)];
[self.view addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_scrollView)];
[self.view addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label1]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(label1)];
[_scrollView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label2]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(label2)];
[_scrollView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[label1]-[label2]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(label1, label2)];
[_scrollView addConstraints:constraints];
}
return self;
}
我认为这段代码有几个结果很奇怪。如果您在viewDidLayoutSubviews
方法中记录scrollviewheight(在超级调用之后),这是应该应用所有约束的地方,那么高度报告为0。同样奇怪的是宽度报告的数字与我预期的不同。由于第一个约束,我希望它报告超级视图的宽度(我什至尝试强制该约束内的宽度具有据称需要的优先级,但它仍然不起作用)。
据我了解,UIScrollView
的内容大小应该由其内容的内在大小设置,但这似乎并没有发生。
那么,有人知道缺少什么吗?