如何将自定义标题视图设置到导航栏的中心

问题描述 投票:1回答:2

我正在尝试将自定义视图(标签)添加为导航项的标题视图。

但它没有出现在中间

func setupNavigationMultilineTitle(title:String) {
        let autoscrollLabel = EFAutoScrollLabel()
        autoscrollLabel.text =  title
        autoscrollLabel.textAlignment = .center
        autoscrollLabel.backgroundColor = .red

        autoscrollLabel.font = AppTheme.Fonts.font(type: .Medium, size: 15)
        autoscrollLabel.textColor = AppTheme.Colors.ColorsOfApp.header_color.color
        autoscrollLabel.frame = CGRect(x: 0, y: 0, width:((self.navigationController?.navigationBar.frame.size.width ?? 0) - (self.navigationItem.leftBarButtonItem?.customView?.frame.width ?? 0) * 2) , height: 40)
        self.navigationItem.titleView = autoscrollLabel

    }

我尝试使用自定义视图的扣除宽度在中心显示它,但不幸的是它不起作用。

我也尝试获取self.navigationItem.leftBarButtonItem.width,但它返回0。我确认存在带有po self.navigationItem.leftBarButtonItem的leftBarbutton项

编辑

这解决了问题

    autoscrollLabel.frame = CGRect(x: self.view.center.x - 125, y: 0, width: 250 , height: 40)

但是我需要动态解决方案

enter image description here

任何帮助将不胜感激

ios uinavigationcontroller uinavigationbar uinavigationitem
2个回答
2
投票

我调试了您的方案,希望它对您和其他开发人员有帮助,

[当我们通过减去项目,边距,填充等的空间后,通过计算剩余的空间来分配titleView宽度,然后iOS从右侧(即titleview.x = rightItem.x - width)计算titleView X,我们期望它像titleview.x = navbar.width/2 - width/2

请在下面的示例测试用例中查看。


计算宽度

let maxItemOnEitherSide = max(arrLeftItems.count, arrRightItems.count)
let widthOfItem : CGFloat = 30.0
let pading : CGFloat = 40

let aWidth : CGFloat = (self.navigationController?.navigationBar.frame.width)! - CGFloat(maxItemOnEitherSide) * widthOfItem * 2.0 - pading

let lblNavTitle = UILabel(frame: CGRect(x: 0, y: 0,
                                        width: aWidth,
                                        height: 40))

案例1: arrLeftItems.count = 1和arrRightItems.count = 0。

输出:

enter image description here

案例2: arrLeftItems.count = 0和arrRightItems.count = 1。

enter image description here


希望以上案例可以使您清楚我们的期望,得到的结果以及我在第一段即titleview.x = rightItem.x - width中编写的计算结果。

结论:

如果rightBarItems的项目多于leftBarItems,则titleview将位于中心,因此您无需执行任何操作,但如果leftBarItems的项目比rightBarItems多,则在右侧添加空白项目以使其平衡。对于开发人员来说很奇怪,但似乎是唯一的解决方案。

检查最终输出。

  • 查看层次结构

enter image description here

  • 输出

enter image description here


0
投票

如果导航项是UINavigationController的一部分,则可以尝试self.navigationController?.navigationBar.topItem?.leftBarButtonItem?.width ?? 0.0

© www.soinside.com 2019 - 2024. All rights reserved.