Multiline Navigationbar Title

后端 未结 3 777
不知归路
不知归路 2020-12-03 18:03

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 t

相关标签:
3条回答
  • 2020-12-03 18:37

    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.

    0 讨论(0)
  • 2020-12-03 18:41

    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 5.x:

    let label = UILabel()
    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
    
    0 讨论(0)
  • 2020-12-03 18:51

    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.

    0 讨论(0)
提交回复
热议问题