Search code examples
iosswiftnslayoutconstraint

NSLayoutConstraints not working in reference to view


I want to create a container view based on the view size. The code speaks for itself but it doesn't work. I've tried using override viewWillAppear to no avail.

import UIKit

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UITextFieldDelegate {

let searchBarContainer: UIView = {
    let sBarContainer = UIView()
    sBarContainer.backgroundColor = UIColor.gray
    return sBarContainer
}()



override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Search Bar"
    collectionView?.backgroundColor = UIColor.white

    view.addSubview(searchBarContainer)

    NSLayoutConstraint(item: searchBarContainer, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0).isActive = true

    NSLayoutConstraint(item: searchBarContainer, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0).isActive = true

    NSLayoutConstraint(item: searchBarContainer, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true

   }


}

Any suggestions? Thanks


Solution

  • Creating NSLayoutConstraints like that will just return the constraint. You either need to add them to the Parent view, or if you're iOS 8+ you can use the much superior Layout Anchors.

    So, for example:

    NSLayoutConstraint(item: searchBarContainer, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0).isActive = true

    becomes

    label.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

    edit: and to be clear, the anchor route means you don't have to deal with manually adding them after creating them.