Reputation: 3430
I'm trying to create custom titleView and change the position to be next to the back button.
The titleView should be look like :
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
Upvotes: 1
Views: 2463
Reputation: 1144
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
Upvotes: 1
Reputation: 1213
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
Upvotes: 0