【问题标题】:Wrong NSLayoutConstraint Causes Black Screen错误的 NSLayoutConstraint 导致黑屏
【发布时间】: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


    【解决方案1】:

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

    self.view.translatesAutoresizingMaskIntoConstraints = false
    

    这样就解决了问题。我认为这会导致应用程序为超级视图创建约束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 2012-11-08
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多