Search code examples
swiftconstraintsuinavigationbartitleview

how to set leading and trailing constraint for a xib used as titleView


I have Xib file with two labels, left and right. left one has 0 on leading and right 0 on trailing. in between a >= 15 constraint. This view is used as title view in a navigation bar. My Question is: How to set this xib in order to get left label close to leftItem and right one close to the rightItem?

how the xib is called

headerVC = HeaderViewController(nibName: "HeaderViewController", bundle: nil)

how the xib is filled

    navigationItem.titleView = headerVC?.view
                headerVC?.lbl1.text = name
                headerVC?.lbl2.text = balance

//test purpose
                    //        headerVC?.backgroundColor = .red
                    //this try of mine not working
                    let leftWidth = self.navigationItem.leftBarButtonItem?.width ?? 0.0
        let rightWidth = self.navigationItem.rightBarButtonItem?.width ?? 0.0
        let sides = leftWidth + rightWidth
        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width
//        NSLayoutConstraint.activate([
//            headerVC?.view.width = screenWidth - leftWidth - rightWidth
        headerVC?.view.widthAnchor.constraint(equalToConstant: screenWidth - sides).isActive = true
//        ])

solution, related to the answer below and to this answer

        headerVC?.backgroundColor = .red
        headerVC?.view.translatesAutoresizingMaskIntoConstraints = false
        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width
        headerVC?.view.widthAnchor.constraint(equalToConstant: screenWidth * 0.75).isActive = true

Solution

  • Your constraints configure the title view to be as small as possible while still showing the labels. If you want the title view to be wider, you will have to add a width constraint making it wider. The title view cannot "see" the left and right items in the nav bar in any way; you'll just have to figure out what the width should be, yourself, and set it.

    Here's an example; the title view is given a width constraint of 100 and 250, respectively.

    enter image description here

    enter image description here

    So for example the second one is

    let v = UIView()
    v.backgroundColor = .red
    v.translatesAutoresizingMaskIntoConstraints = false
    v.widthAnchor.constraint(equalToConstant: 250).isActive = true
    v.heightAnchor.constraint(equalToConstant: 20).isActive = true
    self.navigationItem.titleView = v