添加NSLayoutConstraint后,视图消失

问题描述:

当我将NSLayoutConstraint添加到视图时,它导致视图消失。添加NSLayoutConstraint后,视图消失

我使用下面的代码:

let test:UIView = UIView(frame: CGRectMake(0, 0, 100, 100)) 
test.backgroundColor = UIColor.blackColor() 
self.view.addSubview(test) 
test.translatesAutoresizingMaskIntoConstraints = false 
let topCKCtr = NSLayoutConstraint(item: test, attribute: .CenterX, relatedBy: .Equal, toItem: test.superview, attribute: .CenterX, multiplier: 0.5, constant: 0) 
topCKCtr.active = true 

let topCKCtr1 = NSLayoutConstraint(item: test, attribute: .CenterY, relatedBy: .Equal, toItem: test.superview, attribute: .CenterY, multiplier: 0.5, constant: 0) 
topCKCtr1.active = true 


self.view.layoutIfNeeded() 
self.view.setNeedsDisplay() 

当调试视图层次,我看到的观点存在,即使它是不可见的。有关详细信息,请参见下面的屏幕截图 - 只有约束是可见的,而不是视图: enter image description here

+0

一旦你开始使用约束代码,你需要定义的一切。框架不再使用,因此为宽度和高度添加约束。 – vacawama

有很多事情需要在这里讨论。

  1. 当您使用以下

    test.translatesAutoresizingMaskIntoConstraints = false 
    

    然后,它会完全依靠约束定位和大小view.So你需要设置的高度和角度的宽度限制。

    let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100) 
    
    let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100) 
    

最后这将是你正在寻找

  let test:UIView = UIView(frame: CGRectMake(0, 0, 100, 100)) 
    test.backgroundColor = UIColor.blackColor() 
    self.view.addSubview(test) 
    test.translatesAutoresizingMaskIntoConstraints = false 
    let topCKCtr = NSLayoutConstraint(item: test, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 0.5, constant: 0) 
    topCKCtr.active = true 
    let topCKCtr1 = NSLayoutConstraint(item: test, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 0.5, constant: 0) 
    topCKCtr1.active = true 

    let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100) 
    topCKCtr2.active = true 

    let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100) 
    topCKCtr3.active = true 
+1

您不必将约束添加到视图。将'active'属性设置为'true'可以激活约束条件,'iOS'负责将它们添加到适当的视图中。 – vacawama

+0

你是对的,虽然我加了一段代码,我没有注意到活动部分。 – SunilG

+1

事实上,你可以在一次调用'NSLayoutConstraint.activateConstraints(_ :)'时激活所有的约束,'NSView.addConstraint(_ :)'的文档建议不要再使用'addConstraint'。如果您编辑您的答案以删除过期的电话,您将获得更多赞成票。 –