Search code examples
iosswiftnslayoutconstraint

Layout constraints are not working iOS swift


I added leading | trailing | top | height constraints but the view is not visible.

  let view = UIView()
  view.backgroundColor = .orange
  self.addSubview(view)
    
  NSLayoutConstraint.activate([
        view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        view.topAnchor.constraint(equalTo: self.topAnchor, constant: 100),
        view.heightAnchor.constraint(equalToConstant: 300)
  ])

Solution

  • Your code should disable translatesAutoresizingMaskIntoConstraints when adding the view as a subview. This means the system won't create a set of constraints that duplicate the behaviour specified by the view’s autoresizing mask.

    Assuming your constraints are correct, you should see your view appear after setting the property to false.

    let view = UIView()
    view.backgroundColor = .orange
    view.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(view)
        
    NSLayoutConstraint.activate([
        view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        view.topAnchor.constraint(equalTo: self.topAnchor, constant: 100),
        view.heightAnchor.constraint(equalToConstant: 300)
    ])