所以我继承的应用程序的原始设置具有这样设置的导航栏(这是在我的 AppDelegate 中):
private func configureNavigationController(_ navigationController: UINavigationController) {
navigationController.navigationBar.isTranslucent = false
self.window?.rootViewController = navigationController
let imageView = UIImageView(image: UIImage(named: "logo-white"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let center = (navigationController.topViewController?.view.frame.width)! / 2.0 - 44
let titleView = UIView(frame: CGRect(x: center, y: 0, width: 88, height: 44))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
UINavigationBar.appearance().barTintColor = UIColor.navBackground
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().addSubview(titleView)
}
这会正确地在每个 View Controller 上创建导航栏,图像位于中心,但是我有一些新功能需要放在所有内容之上,并且这个 Logo 文件 - logo-white - 仍然显示在顶部.
这才是我想要解决的真正问题 - 所以如果我在下面尝试的解决方案是错误的,请告诉我并告诉我正确的方法。
无论如何,我尝试在我的 AppDelegate 中注释掉上面的代码,并将其放入我需要它的特定 View Controller 中
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: UIImage(named: "logo-white"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let center = (navigationController!.topViewController?.view.frame.width)!// / 2.0 - 44
let titleView = UIView(frame: CGRect(x: center, y: 0, width: 88, height: 44))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
navigationItem.titleView = imageView
但这不起作用 - 我可以让 Logo 显示在屏幕左侧,或者稍微偏离中心,但永远不会居中。
我猜这是因为该栏的两侧都有一个后退按钮和一个小设置图标。
那么,我该如何正确地做到这一点呢?
有没有办法让它可以覆盖 Logo ?是将它移到我的个人 View Controller 中的解决方案吗?
这是此处重叠的图片。 Logo “Pinyada”根本不应该掩盖这一点——这是一个第三方图书馆,应该位于一切之上。
最佳答案
你可以试试这个:
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: UIImage(named: "logo-white"))
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: 0, y: 0, width: 88, height: 44)
navigationItem.titleView = imageView
}
如果您有 navigationItem.titleView
,则不需要另一个 titleview。
有时候,如果你需要更精确地控制titleView,你可以添加一个customTitleView。在viewController中添加如下代码,就可以得到你想要的。
let imageView = UIImageView(image: UIImage(named: "logo-white"))
private func addTitleView(){
let nbar = (navigationController?.navigationBar)!
let width = nbar.frame.width
imageView.contentMode = UIView.ContentMode.scaleAspectFit
imageView.frame = CGRect.init(x: (width - 88) / 2.0 , y: 0, width: 88, height: 44)
nbar.addSubview(imageView)
}
private func removeTitleView(){
imageView.removeFromSuperview()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addTitleView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeTitleView()
}
顺便说一句,UINavigationBar.appearance().addSubview(titleView)
此方法将导致所有 navigationBar 具有相同的 titleView,这不是您想要的。
关于ios - viewcontroller 的 header 不适合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53013590/