ios - 错误的NSLayoutConstraint导致黑屏

标签 ios swift nslayoutconstraint

我想使用 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/

相关文章:

objective-c - 使用另一个类的方法中的数据更新 View

ios - 如何使用同一个函数创建多个UIView

ios - UINavigationControllerDelegate 破坏了 PushViewController

ios - 阅读更多 UIButton 上的单元格高度增加问题

ios - 修复了 UIStackview subview 的高度限制

ios - WatchKit 通知标题颜色

ios - 当用户单击特定日期时,将显示带有该事件标题的警报

ios - iPad 上的 NSLayoutConstraint SIGABRT

ios - SFSafariViewController : how to provide custom activities?

swift - 弱小的自己去哪儿了?