How to resize Title in a navigation bar dynamically

前端 未结 9 1942
慢半拍i
慢半拍i 2020-12-03 01:24

I have some views that show up in a navigation controller. Two of these views have a longer title for the navigation bar.

The problem is that when the title is too

9条回答
  •  忘掉有多难
    2020-12-03 01:55

    Swift version of Accepted Answer + putting the label text on center :

    Swift 2.3:

        self.title = "Your TiTle Text"
        let tlabel = UILabel(frame: CGRectMake(0, 0, 200, 40))
        tlabel.text = self.title
        tlabel.textColor = UIColor.whiteColor()
        tlabel.font = UIFont.boldSystemFontOfSize(17) //UIFont(name: "Helvetica", size: 17.0)
        tlabel.backgroundColor = UIColor.clearColor()
        tlabel.adjustsFontSizeToFitWidth = true
        tlabel.textAlignment = .Center
        self.navigationItem.titleView = tlabel
    

    And Swift 3 :

        self.title = "Your TiTle Text"
        let frame = CGRect(x: 0, y: 0, width: 200, height: 40)
        let tlabel = UILabel(frame: frame)
        tlabel.text = self.title
        tlabel.textColor = UIColor.white
        tlabel.font = UIFont.boldSystemFont(ofSize: 17) //UIFont(name: "Helvetica", size: 17.0)
        tlabel.backgroundColor = UIColor.clear
        tlabel.adjustsFontSizeToFitWidth = true
        tlabel.textAlignment = .center
        self.navigationItem.titleView = tlabel
    

提交回复
热议问题