问题描述
我的 navigationItem.title 行为很奇怪。
当 viewController 被推入堆栈时,标题没有显示(上图)。然而,当 viewController 被弹出时,标题会在一纳秒左右的时间内可见(见下图)。
这就是我设置标题和添加 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
初始化后修复了问题。