Swift 5 - navigationItem.title 未显示

问题描述

我的 navigationItem.title 行为很奇怪。

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

enter image description here

enter image description here

这就是我设置标题添加 barButtons 的方式。全部在 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,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,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

初始化后修复了问题。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...