【发布时间】:2018-07-04 14:45:47
【问题描述】:
我想用 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])
}
【问题讨论】:
标签: ios swift nslayoutconstraint