1

I'm trying to create custom titleView and change the position to be next to the back button.

The titleView should be look like :

screenshot

So what i did was :

private func setupNavigationItems() {

    let label = UILabel()

    label.translatesAutoresizingMaskIntoConstraints = false

    label.text = "Info"
    label.textColor = UIColor.black
    label.textAlignment = .left
    navigationItem.titleView = label

    if let navigationBar = navigationController?.navigationBar {
        label.widthAnchor.constraint(equalTo: navigationBar.widthAnchor, constant: -40).isActive = true
    }

    self.navigationController?.navigationBar.tintColor = UIColor.black
}


override func updateViewConstraints() {
    super.updateViewConstraints()
    setupNavigationItems()
}

It works, but in some situation i get crash :

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors and because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'

How can i fix this crash?, there is a better way to change the position of the navigation title?

Thanks

Maor
  • 3,340
  • 3
  • 29
  • 38

2 Answers2

1

To get that effect you want to use:

navigationItem.backBarButtonItem

and not:

navigationItem.titleView

the backBarButtonItem will automatically show the title of your previous viewcontroller but can be modified to anything you like as shown here:

How to set back button text in Swift

Trevor
  • 1,075
  • 11
  • 15
0

replace this code :-

label.widthAnchor.constraint(equalTo: navigationBar.widthAnchor, constant: -40).isActive = true

with this code :-

label.widthAnchor.constraint(equalTo: navigationBar.widthAnchor, multiplier: 0.8).isActive = true

Change multiplier according your need.

OR

set frame of UILabel without constraint.

let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width * 0.8, height: 44))
lbl.text = "Info"
lbl.textColor = .black
lbl.textAlignment = .left
navigationItem.titleView = lbl
Datt Patel
  • 1,203
  • 1
  • 11
  • 10