Multiline Navigationbar Title

2019-01-15 10:07发布

I am trying to set the title label in my navigation bar to allow multiple lines. I have custom navigation controller code that I am placing the multiline code into. I know that the code already there works, but my multiline part is not working.

let titleLabel = UILabel()
titleLabel.frame = CGRectMake(0, 0, self.navigationBar.frame.width, self.navigationBar.frame.height * 2)
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .ByWordWrapping

navigationItem.titleView = titleLabel

But the text still runs off at the end. I've also tried putting this into the individual view controller itself, adding self.navigationController?. in front of navigationItem with the same results.

Is there something I'm missing in my code that would keep the title label from using multiple lines?

3条回答
beautiful°
2楼-- · 2019-01-15 10:34

Here is a code example of how you can create a multiline navigationBar title

let label: UILabel = UILabel(frame: CGRectMake(0, 0, 400, 50))
label.backgroundColor = UIColor.clearColor()
label.numberOfLines = 2
label.font = UIFont.boldSystemFontOfSize(16.0)
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label

Swift 3.0:

let label = UILabel(frame: CGRect(x:0, y:0, width:400, height:50))
label.backgroundColor = .clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = .white
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label
查看更多
Lonely孤独者°
3楼-- · 2019-01-15 10:46

Use this to get the label position exactly as you want it:

let labelWidth = navBar.bounds.width - 110

    let label = UILabel(frame: CGRect(x:(navBar.bounds.width/2) - (labelWidth/2), y:0, width:labelWidth, height:navBar.bounds.height))
    label.backgroundColor = UIColor.clear
    label.numberOfLines = 0
    label.font = UIFont.boldSystemFont(ofSize: 13.0)
    label.textAlignment = .center
    label.textColor = UIColor.black
    label.lineBreakMode = .byWordWrapping

    label.text = loadedName
    navBar.topItem?.title = nil
    navBar.addSubview(label)

the 110 value in the top line is the spacing you want either side of the label.

查看更多
成全新的幸福
4楼-- · 2019-01-15 10:55

This is doable in a storyboard. Just drag a UIView into the Navigation bar, then drag a UILabel onto it in the document outline, set lines to 2 and alignment to center.

enter image description here

查看更多
登录 后发表回答