当UITextView 的文本内容相对较短时,内容视图的子视图(即文本视图和页脚)将无法通过约束来决定其内容视图的大小。这是因为当文本内容很短时,内容视图的大小将需要由滚动视图的大小决定。
更新:后一段是不真实的。您可以在内容视图本身或内容视图的视图层次结构中的某处安装固定高度约束。固定高度约束的常量可以在代码中设置以反映滚动视图的高度。后一段也反映了思想上的谬误。在纯自动布局方法中,内容视图的子视图不需要指定滚动视图的contentSize;相反,内容视图本身最终必须决定contentSize。
无论如何,我决定采用 Apple 所谓的“混合方法”来使用 UIScrollView 的自动布局(请参阅 Apple 的技术说明:https://developer.apple.com/library/ios/technotes/tn2154/_index.html)
一些 iOS 技术作家,例如 Erica Sadun,喜欢在几乎所有情况下使用混合方法(“iOS Auto Layout Demystified”,第 2 版)。
在混合方法中,内容视图的框架和滚动视图的内容大小在代码中明确设置。
这是我为此挑战创建的 GitHub 存储库:https://github.com/bilobatum/StickyFooterAutoLayoutChallenge。这是一个有效的解决方案,带有布局更改的动画。它适用于不同尺寸的设备。为简单起见,我禁用了横向旋转。
对于那些不想下载和运行 GitHub 项目的人,我在下面列出了一些亮点(要完整的实现,你必须查看 GitHub 项目):
内容视图为橙色,文本视图为灰色,粘性页脚为蓝色。滚动时,文本在状态栏后面可见。我实际上不喜欢那样,但它可以作为演示。
故事板中唯一实例化的视图是滚动视图,它是全屏的(即,下重叠状态栏)。
出于测试目的,我将双击手势识别器附加到蓝色页脚以关闭键盘。
- (void)viewDidLoad
{
[super viewDidLoad];
self.scrollView.alwaysBounceVertical = YES;
[self.scrollView addSubview:self.contentView];
[self.contentView addSubview:self.textView];
[self.contentView addSubview:self.stickyFooterView];
[self configureConstraintsForContentViewSubviews];
// Apple's mixed (a.k.a. hybrid) approach to laying out a scroll view with Auto Layout: explicitly set content view's frame and scroll view's contentSize (see Apple's Technical Note TN2154: https://developer.apple.com/library/ios/technotes/tn2154/_index.html)
CGFloat textViewHeight = [self calculateHeightForTextViewWithString:self.textView.text];
CGFloat contentViewHeight = [self calculateHeightForContentViewWithTextViewHeight:textViewHeight];
// scroll view is fullscreen in storyboard; i.e., it's final on-screen geometries will be the same as the view controller's main view; unfortunately, the scroll view's final on-screen geometries are not available in viewDidLoad
CGSize scrollViewSize = self.view.bounds.size;
if (contentViewHeight < scrollViewSize.height) {
self.contentView.frame = CGRectMake(0, 0, scrollViewSize.width, scrollViewSize.height);
} else {
self.contentView.frame = CGRectMake(0, 0, scrollViewSize.width, contentViewHeight);
}
self.scrollView.contentSize = self.contentView.bounds.size;
}
- (void)configureConstraintsForContentViewSubviews
{
assert(_textView && _stickyFooterView); // for debugging
// note: there is no constraint between the subviews along the vertical axis; the amount of vertical space between the subviews is determined by the content view's height
NSString *format = @"H:|-(space)-[textView]-(space)-|";
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:@{@"space": @(SIDE_MARGIN)} views:@{@"textView": _textView}]];
format = @"H:|-(space)-[footer]-(space)-|";
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:@{@"space": @(SIDE_MARGIN)} views:@{@"footer": _stickyFooterView}]];
format = @"V:|-(space)-[textView]";
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:@{@"space": @(TOP_MARGIN)} views:@{@"textView": _textView}]];
format = @"V:[footer(height)]-(space)-|";
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:@{@"space": @(BOTTOM_MARGIN), @"height": @(FOOTER_HEIGHT)} views:@{@"footer": _stickyFooterView}]];
// a UITextView does not have an intrinsic content size; will need to install an explicit height constraint based on the size of the text; when the text is modified, this height constraint's constant will need to be updated
CGFloat textViewHeight = [self calculateHeightForTextViewWithString:self.textView.text];
self.textViewHeightConstraint = [NSLayoutConstraint constraintWithItem:self.textView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0f constant:textViewHeight];
[self.textView addConstraint:self.textViewHeightConstraint];
}
- (void)keyboardUp:(NSNotification *)notification
{
// when the keyboard appears, extraneous vertical space between the subviews is eliminated–if necessary; i.e., vertical space between the subviews is reduced to the minimum if this space is not already at the minimum
NSDictionary *info = [notification userInfo];
CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
double duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGFloat contentViewHeight = [self calculateHeightForContentViewWithTextViewHeight:self.textView.bounds.size.height];
CGSize scrollViewSize = self.scrollView.bounds.size;
[UIView animateWithDuration:duration animations:^{
self.contentView.frame = CGRectMake(0, 0, scrollViewSize.width, contentViewHeight);
self.scrollView.contentSize = self.contentView.bounds.size;
UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardRect.size.height, 0);
self.scrollView.contentInset = insets;
self.scrollView.scrollIndicatorInsets = insets;
[self.view layoutIfNeeded];
} completion:^(BOOL finished) {
[self scrollToCaret];
}];
}
虽然这个演示应用的自动布局组件花费了一些时间,但我在与 UITextView 嵌套在 UIScrollView 中相关的滚动问题上花费的时间几乎一样多。