不能以编程方式填写视图的superview

时间:2014-12-29 15:21:00

标签: ios xcode swift autolayout

我会尝试将子视图的大小与其超级视图相同。

override func viewDidLayoutSubviews() {
    subView.setTranslatesAutoresizingMaskIntoConstraints(true)
    let viewsDictionary = ["subView": subView]

    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]|", options: nil, metrics: nil, views: viewsDictionary))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|", options: nil, metrics: nil, views: viewsDictionary))
}

enter image description here 我做错了什么?

=========================

更新!

subView.setTranslatesAutoresizingMaskIntoConstraints(false)
        let viewsDictionary = ["subView": subView]

        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0.0-[subView]-0.0-|", options: nil, metrics: nil, views: viewsDictionary))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0.0-[subView]-0.0-|", options: nil, metrics: nil, views: viewsDictionary))
    }

但没有效果=(

很多!

1 个答案:

答案 0 :(得分:0)

两个错误(至少)。第一:

subView.setTranslatesAutoresizingMaskIntoConstraints(true)

必须是false,而不是true

第二:你不想在viewDidLayoutSubviews中简单地执行此操作,因为在应用程序的生命周期中会多次调用该方法,并且每次都会无条件地添加新约束。