2017-08-17 93 views
1

我有一个带有可变长度标题的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

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

请帮我解决这个问题

+0

变化宽度至设备宽度和titleLabel它对准中心。 –

回答

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 
+0

您是否知道为什么此解决方案与我的其他视图具有相同字体大小相比降低了我的标题文本?看到这里:http://imgur.com/a/LnQzp – MarksCode

+0

对不起,设置你的字体标签...标签字体未设置在此代码..是问题,然后增加高度 –

+0

我。这里是我的完整代码与您的解决方案:https://gist.github.com/MarksCode/ea14a0a984fd8384399893c2d987ebb8 – MarksCode

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

+0

这不会使问题中要求的导航栏中的标签居中。 – rmaddy