UIScrollView具有粘性页脚UIView和动态高度内容

时间:2014-02-11 04:04:41

标签: ios uiview uiscrollview autolayout sticky-footer

挑战时间!

想象一下,我们有2个内容视图:

  1. 具有动态高度内容的UIView(可扩展的UITextView)= RED
  2. UIView作为页脚= BLUE
  3. 此内容位于UIScrollView = GEEN

    如何使用自动布局来构建和处理约束以存档以下所有情况?

    我正在考虑下一个基本结构:

    - UIScrollView (with always bounce vertically)
        - UIView - Container
           - UIView - DynamicHeightContent
           - UIView - Sticky Footer
    

    键盘处理应通过代码观看通知UIKeyboardWillShowNotificationUIKeyboardWillHideNotification来完成。我们可以选择将键盘的结束帧高度设置为Container UIView底部引脚约束或UIScrollView底部的contentInset。

    现在,棘手的部分是粘性页脚。

    • 如果有比整个Container View更多的屏幕,我们如何确保粘性页脚UIView保持在底部?
    • 当键盘显示/隐藏时,我们如何知道可用的屏幕空间?我们肯定需要它。
    • 这是我的目的吗?

    谢谢。

    Case recreation

3 个答案:

答案 0 :(得分:5)

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项目):

enter image description here enter image description here

enter image description here enter image description here

enter image description here

内容视图为橙色,文本视图为灰色,粘性页脚为蓝色。滚动时,状态栏后面会显示文本。我实际上并不喜欢这样,但它对于演示来说很好。

在故事板中实例化的唯一视图是滚动视图,它是全屏的(即,状态栏下方)。

出于测试目的,我将双击手势识别器连接到蓝色页脚以解除键盘。

- (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相关的问题。

答案 1 :(得分:0)

使用UIScrollView代替UITableView,你很可能会更好。不使用自动布局也可能更好。至少,我发现最好不要将它用于这些类型的操作。

请查看以下内容:

  • UITextView textViewDidChange
    • 使用sizeThatFits更改文本视图的大小(限制宽度并使用FLT_MAX作为高度)。更改框架,而不是contentSize。
    • 调用UITableView beginUpdates / endUpdates更新表格视图
    • 滚动到光标
  • UIKeyboardWillShowNotification通知
    • NSNotification上,您可以调用userInfo(字典)和密钥UIKeyboardFrameBeginUserInfoKey。根据键盘大小的高度缩小表格视图的框架。
    • 再次滚动到光标(因为布局将全部更改)
  • UIKeyboardWillHideNotification通知
    • 与节目通知相同,正好相反(增加桌面视图高度)

要让页脚视图粘在底部,您可以在表格视图中添加一个中间单元格,并根据文本大小和键盘是否可见来更改大小。

以上肯定会需要一些额外的操作 - 我不完全了解你的所有情况,但它绝对应该让你开始。

答案 2 :(得分:0)

如果我理解整个任务,我的解决方案是将“红色”和“蓝色”视图放到一个容器视图中,并且在您知道动态内容大小(红色)的那一刻,您可以计算容器的大小并设置scrollView内容尺寸。 稍后,在键盘事件上,您可以调整内容和页脚视图之间的空白区域