Swift 5 - navigationItem.title 未显示

Swift 5 - navigationItem.title not showing

我的 navigationItem.title 行为很奇怪。

当 viewController 被推入堆栈时,标题未显示(上图)。然而,当 viewController 弹出时,标题会在一纳秒左右可见(见下图)。

这就是我设置标题和添加栏按钮的方式。尽在 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)

更新 我的视图层次结构是 NavigationController -> AnotherViewController -> ThisViewController

我的错误在哪里?什么隐藏标题?

我不确定你的视图控制器在什么层次结构中,但你可以设置标题,如下所示,

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" 
}

好的,所以问题是我的 backBtnView - 尽管将其框架设置为宽度 = 30 - 覆盖了标题。

我通过为视图设置黑色背景色发现了这一点。视野竟然比 30 宽得多。

正在做

backBtnView.frame.size.width = 30

初始化后问题得到解决。