我一直在尝试在 UIScrollView 上实现自动布局,但一直在苦苦挣扎。这是我的主视图的描述,从上到下:导航栏 -> 滚动视图 -> UITextField,所有这些都在屏幕上水平拉伸。以下是这三个视图的约束:
//Vertical constraints; this appears to be working fine
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-navHeight-[_inputScrollView][_inputField(inputFieldHeight)]|" options:0 metrics:metricsDict views:viewsDict]];
//Horizontal Constraints; these also appear to be working fine
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_inputScrollView]|" options:0 metrics:metricsDict views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_inputField]|" options:0 metrics:metricsDict views:viewsDict]];
接下来,正如无数 UIScrollView/autolayout 教程所建议的那样,我在 UIScrollView 中添加了一个子视图,以充当许多其他子视图的内容视图,这些子视图将在运行时动态添加。因此,当应用程序启动时,内容视图中将没有任何内容。以下是我的内容视图的约束:
//Left constraint, pinning the content view to the left edge of the screen
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:_contentView
attribute:NSLayoutAttributeLeading
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:0];
[self.view addConstraint:leftConstraint];
//Right constraint, pinning the content view to the left edge of the screen
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:_contentView
attribute:NSLayoutAttributeTrailing
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:0];
[self.view addConstraint:rightConstraint];
//Top constraint, setting the top of the content view
//to be offset from the top of the main view
//by the height of the navigation bar
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:_contentView
attribute:NSLayoutAttributeTop
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:navHeight.floatValue];
[self.view addConstraint:topConstraint];
//Bottom constraint, setting the bottom of the content view
//to be offset from the bottom of the main view by the
//height of the text field.
NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:_contentView
attribute:NSLayoutAttributeBottom
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:-inputFieldHeight.floatValue];
[self.view addConstraint:bottomConstraint];
布置完这些视图后,我的内容视图的高度等于我的滚动视图的高度。我将 alwaysBounceVertical 属性设置为 YES,所以我希望看到一些滚动。当我在屏幕上滚动时,滚动视图的内容偏移量确实发生了变化!我实现了 scrollViewDidScroll 并将 contentOffset 记录到屏幕上。但是,内容视图根本不动。我将滚动视图的背景颜色设置为红色,将内容视图的背景颜色设置为黑色。当 contentOffset 发生变化时,您仍然看不到任何红色滚动视图。内容视图是滚动视图的子视图,为什么它的框架没有改变?!任何帮助都会非常感激。谢谢!