错误的NSLayoutConstraint导致黑屏

时间:2018-07-04 14:45:48

标签: ios swift nslayoutconstraint

我想使用NSLayoutConstraint将标头视图放在屏幕顶部(我必须使用NSLayoutConstraint)。当我像下面的代码那样执行操作时,在其他地方查看位置损坏,并且控制器的背景颜色变为黑色,并且没有任何效果。我在哪里做错了?

我在下面的帖子中搜索了是否未打开重复的帖子,但没有修复它:

Programmatically creating constraints bound to view controller margins

Programmatically Add CenterX/CenterY Constraints

编辑:此控制器位于导航控制器内部,但是我不确定是否相关。

override func viewDidLoad(){
    self.view.backgroundColor = UIColor.white

    boxView.backgroundColor = Color.Common.welcomeScreenBackgroundColor.withAlphaComponent(0.5)
    boxView.translatesAutoresizingMaskIntoConstraints = false
    self.view.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubView(boxView)
}
override func viewDidLayoutSubviews() {

//Header = 20 from left edge of screen
let cn1 = NSLayoutConstraint(item: boxView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0)
//Header view trailing end is 20 px from right edge of the screen
let cn2 = NSLayoutConstraint(item: boxView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0)
//Header view height = constant 240
let cn3 = NSLayoutConstraint(item: boxView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant:240)
//Header view vertical padding from the top edge of the screen = 20
let cn5 = NSLayoutConstraint(item: boxView, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)

self.view.addConstraints([cn1,cn2,cn3,cn5])
}

1 个答案:

答案 0 :(得分:0)

问题是在translatesAutoresizingMaskIntoConstraints上将Superview设置为false。所以我删除了;

self.view.translatesAutoresizingMaskIntoConstraints = false

这解决了问题。我认为这会导致应用为超级观看创建约束。