0
votes

My navigationItem.title behaves in a strange way.

When the viewController is pushed on to stack the title is not showing (top image). However, while viewController gets popped, the title becomes visible for a nanosecond or so (see bottom image).

enter image description here

enter image description here

This is how I set the title and add the barButtons. All in viewDidLoad.

navigationItem.title = "Mitt konto"
  
let backBtn = UIButton(type: .custom)
let backBtnImage = UIImage(systemName: "chevron.left")
backBtn.setBackgroundImage(backBtnImage, for: .normal)
backBtn.addTarget(self, action: #selector(popViewController), for: .touchUpInside)
backBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)

let backBtnView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
backBtnView.bounds = view.bounds.offsetBy(dx: 0, dy: -10)
backBtnView.addSubview(backBtn)
let backButton = UIBarButtonItem(customView: backBtnView)
navigationItem.leftBarButtonItem = backButton
    
let signOutImage = UIImage(named: "signout_item")?.withTintColor(.white)
let button = UIButton(frame: CGRect(x: 0,y: 0,width: 20, height: 20))
button.setBackgroundImage(signOutImage, for: .normal)
button.addTarget(self, action: #selector(signoutButtonPressed(_:)), for: .touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

UPDATE My view hierarchy is NavigationController -> AnotherViewController -> ThisViewController

Where's my misstake? What is hiding the title?

2
Can you post an example project to GitHub? - matt
first try to debug in console and check your title value. - Kudos
@Kudos, where would be the best place to check for the title value? - Dan Abnormal
when your are setting rightnavigationitem. Make here a breakpoint and check. - Kudos
The value of navigationItem.title is "Mitt konto" when it's set, right before rightBarButtonItem is set and also in viewdidAppear. Thanks for trying to help, but the value is there. Note also in my question that the title appears during pop. - Dan Abnormal

2 Answers

0
votes

I am not sure in what hierarchy your view controller's are but you can set title as shown below,

override func viewDidLoad() { 
super.viewDidLoad()
 /* If view controller is a direct child of UINavigationController */
 self.title = "Title Here" 
/* If view controller's parent is a direct child of UINavigationController e.g. a child of embedded tab view controller */
 self.parent?.title = "Title Here" 
}
0
votes

Ok, so the problem was that my backBtnView - despite setting its frame with width = 30 - was covering the title.

I found this out by giving the view a black background color. The view turned out to be way wider than 30.

Doing

backBtnView.frame.size.width = 30

after initialization fixed the issue.