Swift向UIScrollView子视图添加约束

时间:2016-10-15 04:07:48

标签: ios swift uiscrollview autolayout

我是新手使用子视图但由于某种原因,添加约束scrollView不显示子视图。它仅在使用.frame时有效。请查看我的代码并告知我们。

谢谢。

let scrollView = UIScrollView()
let myView = UIImageView()

override func viewDidLoad() {

    view.addSubview(scrollView)
    scrollView.backgroundColor = .red
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
    scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true

    scrollView.addSubview(myView)
    myView.backgroundColor = .brown
    myView.translatesAutoresizingMaskIntoConstraints = false
    myView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 0).isActive = true
    myView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: 0).isActive = true
    myView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
    myView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true
}

1 个答案:

答案 0 :(得分:1)

这是因为UIScrollView在使用autolayout时与其父级和子级相关的大小。

第一组约束(在scrollview及其父级之间)确保将scrollview的框架固定到根视图的边缘。

第二组约束(在scrollview及其子代之间)只是确保scrollview的内容大小等于子视图的大小。实质上,此约束最终会修改滚动视图的内容大小,而不是子视图的框架。子视图为空白且没有内容,因此其大小为0.这使得scrollview的内容大小为0。

print(scrollView.frame)
(0.0, 0.0, 414.0, 736.0)
print(scrollView.bounds)
(0.0, 0.0, 414.0, 736.0)
print(scrollView.contentSize)
(0.0, 0.0)
print(myView.frame)
(0.0, 0.0, 0.0, 0.0)

此行为在此technical note中有所解释。

如果你真正想要的是让子视图填充滚动视图的整个框架,你可以明确地这样做:

myView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
myView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true