Multiline Navigationbar Title

我与影子孤独终老i 提交于 2019-11-26 21:37:26

问题


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?


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/34298383/multiline-navigationbar-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!