0

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

2
  • 1
    You don't have anything setting the x-position of the subview Commented May 24, 2017 at 20:54
  • 3
    You also need to set translatesAutoresizingMaskIntoConstraints to false Commented May 24, 2017 at 20:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.