0

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?

Dan Abnormal
  • 1,188
  • 11
  • 21

2 Answers2

0

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" 
}
ami solani
  • 351
  • 1
  • 5
  • Thanks for helping but none of your suggestions work. As I state in the question, the title gets set. The problem seems to be it's hidden for some reason. However, I will update my question with my view hierarchy. Good point. – Dan Abnormal Mar 27 '21 at 20:42
  • Your hierarchy is clear, but i need more information to debug this issue – ami solani Mar 28 '21 at 05:04
  • Can you Please add whole view controller code – ami solani Mar 28 '21 at 18:09
0

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.

Dan Abnormal
  • 1,188
  • 11
  • 21