Jixes
Jixes

Reputation: 27

After adding an NSLayoutConstraint, view disappears

When I add an NSLayoutConstraint to a view, it results in the view disappearing.

I am using the following code:

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()

When I debug view hierarchy, i see that the view exists, even though it is not visible. See the below screenshot for details - only the constraint is visible, not the view: enter image description here

Upvotes: 0

Views: 999

Answers (1)

SunilG
SunilG

Reputation: 121

There are so many things that needs to be discussed here.

  1. When you use the following

    test.translatesAutoresizingMaskIntoConstraints = false
    

    Then it will totally rely on constraints to position and size a view.So you need to set height and width constraints of the view.

    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)
    

Finally This will be the code which you are looking for

            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

Upvotes: 1

Related Questions