自动调整大小的navigationBar标题放错地方

时间:2017-08-17 06:59:02

标签: ios uinavigationbar

我有一个UINavigationBar,标题可变长度。为确保标题适合而不被截断,我已在 viewDidLoad()中实施了以下代码:

let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
titleLabel.text = "\(petsName)'s Day"
titleLabel.font = UIFont.systemFont(ofSize: 30)
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.white
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = 0.5
self.navBar.topItem?.titleView = titleLabel

但是,因为我有一个条形按钮项目,标题将被移动到左侧:

navbar

有没有办法实现上面的代码,但保持文本中心在导航栏中对齐?

请帮我解决此问题

2 个答案:

答案 0 :(得分:1)

试试这个..可能有效

var view = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
var label = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
label.text = "Joys Day"
label.textAlignment = .center
 label.font = UIFont.systemFont(ofSize: 30)
view.addSubview(label)
navigationItem?.titleView = view

答案 1 :(得分:1)

titleLabel宽度更改为设备宽度并将其与中心对齐。试试这个:

    let deviceWidth = UIScreen.main.bounds.size.width

    let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: deviceWidth, height: 40))
    titleLabel.text = "My Test Title"
    titleLabel.font = UIFont.systemFont(ofSize: 20)
    titleLabel.backgroundColor = UIColor.clear
    titleLabel.textColor = UIColor.white
    titleLabel.adjustsFontSizeToFitWidth = true
    titleLabel.minimumScaleFactor = 0.5
    titleLabel.textAlignment = .center
    self.navigationItem.titleView = titleLabel

输出: enter image description here