UIScrollView に自動レイアウトを実装しようとしていますが、苦労しています。上から順に、メイン ビューの説明を次に示します。ナビゲーション バー -> スクロール ビュー -> UITextField。これらはすべて、画面全体に水平に伸びています。これら 3 つのビューの制約は次のとおりです。
//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 が変更されている場合でも、赤いスクロールビューは表示されません。コンテンツ ビューはスクロール ビューのサブビューであるのに、なぜそのフレームは変更されないのでしょうか?! どんな助けでもとてもとても感謝しています。ありがとう!