UIScrollView动态高度内容(autolayout)不填充整个空间

时间:2016-02-22 22:07:54

标签: ios swift uiscrollview autolayout

我正在创建一个小型聊天应用程序,其中我使用UIScrollView的自定义子类来显示消息。这个应用程序只是为了练习所以我不想使用第三方库。我正在通过自动布局实现这个UIScrollView,在阅读了Apple的technical note 2154和几个解释这个的教程后,我的实现几乎正常,但我的UIScrollView的内容视图似乎没有填满所有可用空间。

呈现ScrollView的代码是:

public class ChatView: UIScrollView {
    private var contentView: UIView

    ...

    // This get called by all the init methods. contentView is already created ( contentView = UIView() )
    private func setupViews() {
        self.translatesAutoresizingMaskIntoConstraints = false
        contentView.translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(contentView)

        let constraint1 = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1.0, constant: 0.0)
        let constraint2 = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
        let constraint3 = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: contentView, attribute: .Width, multiplier: 1.0, constant: 0.0)
        let constraint4 = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)

        self.addConstraints([constraint1, constraint2, constraint3, constraint4])

        self.layoutIfNeeded()

        // Later, the messages are added to the contentView. I don't think is relevant to see the exact code (but I can post it if needed)
        // Each message is added using autolayout and the constraints only reference the messages themselves and contentView
    }
}

当我将ChatView添加到我的视图控制器(使用故事板)时,将其四边固定到不在其层次结构中的视图,会发生以下问题:

Screenshot of the problem

在图像中,无法再向上滚动scrollView。似乎有一个空间应该填补而不是。如果我向下滚动,我有完全相同的问题,但空白空间低于内容。在下面的图像中,您可以看到contentView最小于ChatView本身:

The debugger view of the problem wo constraints

相同的视图层次结构但显示了约束:

The debugger view of the problem with constraints

在两个图像中,后台视图是ChatView,所选择的视图是contentView。我无法弄清楚为什么内容视图不能覆盖整个ChatView空间。

提前致谢!

1 个答案:

答案 0 :(得分:1)

我在another stackoverflow question搜索其他问题时偶然发现了答案。关键是打开故事板并在容器视图控制器“AdjustsScrollViewInsets”中设置为“NO”。

在代码中它只是(在视图控制器内):

self.automaticallyAdjustsScrollViewInsets = NO;