我想使用 NSLayoutConstraint 将标题 View 放置在屏幕顶部(我必须使用 NSLayoutConstraint)。当我像下面的代码一样执行此操作时, View 位置会在其他地方损坏,并且 Controller 背景颜色会变成黑色,并且没有任何效果。我哪里做错了?
我在下面的帖子中搜索了没有打开重复帖子的问题,但没有任何解决办法:
Programmatically creating constraints bound to view controller margins
Programmatically Add CenterX/CenterY Constraints
编辑:该 Controller 位于导航 Controller 内部,但我不确定它是否相关。
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])
}
最佳答案
问题出在 Superview
上将 translatesAutoresizingMaskIntoConstraints
设置为 false。所以我删除了;
self.view.translatesAutoresizingMaskIntoConstraints = false
这解决了问题。我认为这会导致应用程序对 super View 创建约束。
关于ios - 错误的NSLayoutConstraint导致黑屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51176278/