1

I am trying to programmatically set my constraints to the top of my UIViewController's Nav Bar, but I can't see to get it to work properly. Here is my code:

func setup() {
    let containerView = UIView()
    containerView.backgroundColor = .red
    containerView.translatesAutoresizingMaskIntoConstraints = false

    let payeeNameTextField = UITextField()
    payeeNameTextField.backgroundColor = .green
    payeeNameTextField.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(containerView)
    view.addSubview(payeeNameTextField)

    //iOS 9 Constraints 
    //x,y,w,h

    // Constraint To Nav Bar
    containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    containerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: 20).isActive = true

    // Constraint to Bottom Anchor
    payeeNameTextField.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    payeeNameTextField.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    payeeNameTextField.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    payeeNameTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true


}

I know setting it topAnchor is wrong, but I have tried to mess around with this and just cant seem to get the red background to show up.

Thanks in advance for any input!!

a2b123
  • 573
  • 1
  • 5
  • 19
  • It works for me, I think. The red view shows up *underneath* the status bar, which it should. Your code as posted has **no** nav bar defined, just a red view 20 points in height attached to the top of the view controller's view. –  Apr 01 '17 at 21:15
  • you are right, i know its showing up underneath the nav bar. any ideas on how to pin from the nav bar. i just cant put together the syntax to pin it to the nav bar and not the view's top anchor. – a2b123 Apr 01 '17 at 21:21
  • That depends on one thing - how is your nav bar defined? How did you create it? In code, added through IB, or "embedded" through the IB menu? (I'm guessing it isn't the last one, as your code would work.) –  Apr 01 '17 at 21:27
  • I have not created a nav bar and i am doing everything programmatically. I tried defining my navBar as: `let navBar = navigationController?.navigationItem.titleView?.topAnchor`, unwrapping it: `guard let newNav = navBar else { return }`, and using this as the y constraint: `containerView.topAnchor.constraint(equalTo: newNav).isActive = true`.....but that doesn't seem to be working.. – a2b123 Apr 01 '17 at 21:32
  • I'll offer an answer - if it doesn't work Ill delete it. For my apps I ended a navigation controller through the IB menu, and your code works fine. So if my answer doesn't work, I'd say try it there. –  Apr 01 '17 at 21:42
  • awesome, thank you so much! – a2b123 Apr 01 '17 at 21:55

0 Answers0